英文:
Sort numerically and alphabetically in Python
问题
I have a pandas series, 50K rows and two columns. I need to sort the "syn" column first numerically and then alphabetically.
name | syn |
---|---|
name1 | 1616TD, K25, PP785, 70-07200 |
name2 | WTR-098, 0616TD, K25, PP785, 70-07200 |
name50 | ..... |
So that I get the below output: extra sorted column
name | syn | sorted |
---|---|---|
name1 | 1616TD, K25, PP785, 70-07200 | 1616TD, 70-07200, K25, PP785 |
name2 | WTR-098, 0616TD, K25, PP785, 70-07200 | 0616TD, 70-07200, K25, PP785, WTR-098 |
name50 | ........ |
英文:
I have a pandas series, 50K rows and two columns. I need to sort the "syn" column first numerically and then alphabetically.
name | syn |
---|---|
name1 | 1616TD, K25, PP785, 70-07200 |
name2 | WTR-098, 0616TD, K25, PP785, 70-07200 |
name50 | ..... |
So that I get the below output: extra sorted column
name | syn | sorted |
---|---|---|
name1 | 1616TD, K25, PP785, 70-07200 | 1616TD, 70-07200, K25, PP785 |
name2 | WTR-098, 0616TD, K25, PP785, 70-07200 | 0616TD, 70-07200, K25, PP785, WTR-098 |
name50 | ........ |
The "syn" column is string, may contain hyphens, and spaces after commas. I have shared how the first two rows look like.
答案1
得分: 1
你可以尝试:
df = pd.DataFrame(
{'name':['name1', 'name2'],
'syn':[['1616TD', 'K25', 'PP785', '70-07200'], ['WTR-098', '0616TD', 'K25', 'PP785', '70-07200']]
}
)
df.syn = df.syn.apply(lambda x: sorted(x))
print(df)
结果:
name syn
0 name1 [1616TD, 70-07200, K25, PP785]
1 name2 [0616TD, 70-07200, K25, PP785, WTR-098]
英文:
You can try:
df = pd.DataFrame(
{'name':['name1', 'name2'],
'syn':[['1616TD', 'K25', 'PP785', '70-07200'], ['WTR-098', '0616TD', 'K25', 'PP785', '70-07200']]
}
)
df.syn = df.syn.apply(lambda x: sorted(x))
print(df)
Result:
name syn
0 name1 [1616TD, 70-07200, K25, PP785]
1 name2 [0616TD, 70-07200, K25, PP785, WTR-098]
答案2
得分: 0
如果您想在“syn”列内进行排序,请尝试以下操作:
data["syn"].apply(lambda x: ",".join(sorted(list(map(lambda y: y.strip(), x.split(","))))))
英文:
If you want to sort inside the column syn
try this:
data["syn"].apply(lambda x:",".join(sorted(list(map(lambda y:y.strip(),x.split(","))))))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论