pandas 如何将列表转换为熊猫中的集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33125611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:02:11 来源:igfitidea点击:
How to convert list into set in pandas?
提问by ALH
I have a dataframe as below:
我有一个如下的数据框:
date uids
0 2018-11-23 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
1 2018-11-24 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
When I use setto convert it to set it fails:
当我set用来转换它以设置它失败时:
df['uids'] = set(df['uids']) # IT FAILS!
How should I convert listinto setin place?
我应该如何转换list成set到位?
回答by Gregg
You should use applymethod of DataFrame API:
您应该使用DataFrame API 的apply方法:
df['uids'] = df.apply(lambda row: set(row['uids']), axis=1)
or
或者
df = df['uids'].apply(set) # great thanks to EdChum
You can find more information about applymethod here.
您可以在此处找到有关apply方法的更多信息。
Examples of use
使用示例
df = pd.DataFrame({'A': [[1,2,3,4,5,1,1,1], [2,3,4,2,2,2,3,3]]})
df = df['A'].apply(set)
Output:
输出:
>>> df
0 set([1, 2, 3, 4, 5])
1 set([2, 3, 4])
Name: A, dtype: object
Or:
或者:
>>> df = pd.DataFrame({'A': [[1,2,3,4,5,1,1,1], [2,3,4,2,2,2,3,3]]})
>>> df['A'] = df.apply(lambda row: set(row['A']), axis=1)
>>> df
A
0 set([1, 2, 3, 4, 5])
1 set([2, 3, 4])

