我有一个数据框
IDs Types
0 1001 {251}
1 1013 {251, 101}
2 1004 {251, 701}
3 3011 {251}
4 1014 {701}
5 1114 {251}
6 1015 {251}
其中 df['Types']
在每一行中都有集合。我想将此列转换为多个列,以便获得以下输出
IDs Type1 Type2
0 1001 251 -
1 1013 251 101
2 1004 251 701
3 3011 251 -
4 1014 701 -
5 1114 251 -
6 1015 251 -
目前,我正在使用下面的代码来实现这一点
pd.concat([df['Types'].apply(pd.Series), df['IDs']], axis = 1)
但它返回以下错误
Traceback (most recent call last):
File "C:/Users/PycharmProjects/test/test.py", line 48, in <module>
df = pd.concat([df['Types'].apply(pd.Series), df['IDs']], axis = 1)
File "C:\Python\Python35\lib\site-packages\pandas\core\series.py", line 2294, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas\src\inference.pyx", line 1207, in pandas.lib.map_infer (pandas\lib.c:66124)
File "C:\Python\Python35\lib\site-packages\pandas\core\series.py", line 223, in __init__
"".format(data.__class__.__name__))
TypeError: 'set' type is unordered
请指导我如何获得所需的输出。谢谢
最佳答案
我认为您首先需要 DataFrame
构造函数,然后重命名列,最后 fillna
.
但是如果将 fillna
与某些字符串一起使用,则可能会出现问题,因为将数字与字符串 (-
) 数据混合在一起,并且某些 pandas 函数可能会被破坏。
df1 = pd.DataFrame(df['Types'].values.tolist()) \
.rename(columns = lambda x: 'Type{}'.format(x+1)) \
.fillna('-')
print (df1)
Type1 Type2
0 251 -
1 251 101
2 251 701
df2 = pd.concat([df['IDs'], df1], axis = 1)
print (df2)
IDs Type1 Type2
0 1001 251 -
1 1013 251 101
2 1004 251 701
另一个较慢的解决方案:
df1 = df['Types'].apply(lambda x: pd.Series(list(x))) \
.rename(columns =lambda x: 'Type{}'.format(x+1)) \
.fillna('-')
df2 = pd.concat([df['IDs'], df1], axis = 1)
print (df2)
IDs Type1 Type2
0 1001 251.0 -
1 1013 251.0 101
2 1004 251.0 701
关于python - 将 Set 拆分为多列 Pandas Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43453606/