[英]Pandas merging strings in columns and sorting them
我有三列要合并和排序
x1 x2 x3 x4
US DE None None
FR DE US None
FR None None None
DE CA None None
我想要做的是按字母顺序合并这四列。
merged
DE, US
DE, FR, US
FR
CA, DE
您可以过滤掉None
,排序和加入列表理解应该非常快:
df['merged'] = [', '.join(sorted(filter(None, x))) for x in df.to_numpy()]
使用 lambda 函数的替代方法更慢:
df['merged'] = df.apply(lambda x: ', '.join(sorted(filter(None, x))), axis=1)
print (df)
x1 x2 x3 x4 merged
0 US DE None None DE, US
1 FR DE US None DE, FR, US
2 FR None None None FR
3 DE CA None None CA, DE
如果使用纯DataFrame
方法和大型DataFrame
这应该是最慢的:
s = df.stack().sort_values().groupby(level=0).agg(', '.join)
print (s)
0 DE, US
1 DE, FR, US
2 FR
3 CA, DE
dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.