简体   繁体   English

Pandas Dataframe:对数据框中的列表列进行排序

[英]Pandas Dataframe: Sort list column in dataframe

I have dataframe as below:我有如下数据框:

   |            types |     TypeList
0  |    Q11424 (item) |  Q11424 (item),Q571 (item)
1  |      Q571 (item) |  Q10 (item),Q24 (item)
0  |    Q11012 (item) |  Q3 (item)
0  |  Q4830453 (item) |  Q4 (item)
0  |  Q7725634 (item) |  Q67 (item),Q12 (item)

I want to sort elements in TypeList column in ascending order.我想按升序对 TypeList 列中的元素进行排序。 ie each row of typelist should be sorted based on the integer part of it.即 typelist 的每一行都应该根据它的整数部分进行排序。 I basically want output as below:我基本上想要输出如下:

   |            types |     TypeList
0  |    Q11424 (item) |  Q571 (item),Q11424 (item)
1  |      Q571 (item) |  Q10 (item),Q24 (item)
0  |    Q11012 (item) |  Q3 (item)
0  |  Q4830453 (item) |  Q4 (item)
0  |  Q7725634 (item) |  Q12 (item),Q67 (item)

I am able to remove all characters from this TypeList column, keeping only "," seperated strings and further converted it to list ie each row of this column is now list of type strings.我能够从此 TypeList 列中删除所有字符,只保留“,”分隔的字符串,并进一步将其转换为列表,即此列的每一行现在都是类型字符串列表。 I wanted to apply sort on that, so I did something like below:我想对此应用排序,所以我做了如下操作:

df.TypeList.apply(lambda x: (int(y) for y in x))

but it give result dataframe having all row values as但它给出的结果数据帧具有所有行值

<generator object <lambda>.<locals>.<genexpr> ...

I am not sure how to solve this issue.我不知道如何解决这个问题。 Can someone help me to resolve it.有人可以帮我解决它。

Thanks in advance.提前致谢。

import re
import operator

for i in df.index:
    x = df.loc[i,'TypeList']
    # x ==  'Q11424 (item),Q571 (item)'
    y = x.split(',')
    y = {int(re.search(r'(?<=Q)\d+', k).group(0)):k for k in y}
    # y == {11424: 'Q11424 (item)', 571: 'Q571 (item)'}
    sorted_y = sorted(y.items(), key=operator.itemgetter(0))
    # sorted_y == [(571, 'Q571 (item)'), (11424, 'Q11424 (item)')]
    sorted_x = ','.join([i[1] for i in sorted_y])
    # sorted_x == 'Q571 (item),Q11424 (item)'
    df.loc[i, 'TypeList'] = sorted_x

This one doesn't use apply , as I'm not familiar with it.这个不使用apply ,因为我不熟悉它。 But I hope you get the idea.但我希望你能明白。

Use sorted with parameter key :使用sorted参数key sorted

df = (df['TypeList'].str.split(',')
                   .apply(lambda x:  sorted(x, key=lambda y: int(y.split()[0][1:])))
                   .str.join(','))
print (df)

0    Q571 (item),Q11424 (item)
1        Q10 (item),Q24 (item)
2                    Q3 (item)
3                    Q4 (item)
4        Q12 (item),Q67 (item)
Name: TypeList, dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM