在Python中进行数字和字母的排序。

huangapple go评论97阅读模式
英文:

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

你可以尝试:

  1. df = pd.DataFrame(
  2. {'name':['name1', 'name2'],
  3. 'syn':[['1616TD', 'K25', 'PP785', '70-07200'], ['WTR-098', '0616TD', 'K25', 'PP785', '70-07200']]
  4. }
  5. )
  6. df.syn = df.syn.apply(lambda x: sorted(x))
  7. print(df)

结果:

  1. name syn
  2. 0 name1 [1616TD, 70-07200, K25, PP785]
  3. 1 name2 [0616TD, 70-07200, K25, PP785, WTR-098]
英文:

You can try:

  1. df = pd.DataFrame(
  2. {'name':['name1', 'name2'],
  3. 'syn':[['1616TD', 'K25', 'PP785', '70-07200'], ['WTR-098', '0616TD', 'K25', 'PP785', '70-07200']]
  4. }
  5. )
  6. df.syn = df.syn.apply(lambda x: sorted(x))
  7. print(df)

Result:

  1. name syn
  2. 0 name1 [1616TD, 70-07200, K25, PP785]
  3. 1 name2 [0616TD, 70-07200, K25, PP785, WTR-098]

答案2

得分: 0

如果您想在“syn”列内进行排序,请尝试以下操作:

  1. 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:

  1. data["syn"].apply(lambda x:",".join(sorted(list(map(lambda y:y.strip(),x.split(","))))))

huangapple
  • 本文由 发表于 2023年5月25日 00:36:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76325723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定