python - 将 Set 拆分为多列 Pandas Python

标签 python pandas dataframe

我有一个数据框

        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/

相关文章:

python - Pandas 向量化而不是循环

python - Turtle Python 3,使用用户提供的行数和列数创建一个 "mosaic tile",每个行和列的中间都印有一只 turtle

python - 如何在python和NLTK中计算预测概率?

python - 在 Pandas 中绘制系列直方图

Python Pandas 将一列中的 NaN 替换为同一行另一列中的值作为列表列

python - 从非修复 header 开始的 csv 中读取 Pandas 数据帧

python - Pandas 应用函数删除数据

python - 如何用 python 打开 MP4 视频文件?

python - pandas groupby 并聚合到原始数据帧中

dataframe - 如何在 Spark Dataframe 中显示完整的列内容?