【问题标题】:How to expand pandas column containing values in arrays to multiple columns?如何将包含数组中的值的熊猫列扩展到多列?
【发布时间】:2023-03-11 06:50:01
【问题描述】:

我有一个数据框,其列名为“gear”,其中包含值列表...我现在要做的是将每个列表中的每个元素移动到相应的列。

有没有不需要 for 循环的方法来做到这一点? 例如,在第一行中,列表中的值“Hengerfeste”应移动到列表中的每个元素的“Hengerfeste”列,依此类推。

【问题讨论】:

  • 你为什么不想要一个 for 循环?
  • 需要很长时间的主要问题是多次调用 .iloc 来分配值

标签: arrays pandas list dataframe mapping


【解决方案1】:

试试explode,然后是groupby().value_counts()

#sample data
df = pd.DataFrame({'col':[['a','b','c'], ['a','c','x'],[],['b','x','y']]})


(df['your_list_col'].explode()
   .groupby(level=0).value_counts()
   .unstack(fill_value=0)
   .reindex(df.index, fill_value=0)
)

输出:

col  a  b  c  x  y
0    1  1  1  0  0
1    1  0  1  1  0
2    0  0  0  0  0
3    0  1  0  1  1

【讨论】:

  • 你真是个天才!谢谢这个作品!
猜你喜欢
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 2020-01-24
  • 2022-01-24
  • 1970-01-01
相关资源
最近更新 更多