如果在 jupyter notebook 中使用 python 或 pandas 长度不同,如何将列中的逗号分隔字符串拆分为不同的列

How to split comma separated strings in a column into different columns if they're not of same length using python or pandas in jupyter notebook

我正在学习 python 并处理示例 Kaggle 数据集,并尝试在 jupyter notebook 中使用 python 或 pandas 将一列中的逗号分隔值拆分为不同的列。

例如:

column_A

垃圾:纸巾,有机物:牛奶,回收:纸板

垃圾:纸巾,有机物:鸡蛋,回收:玻璃,垃圾:粪便

垃圾:杯子,回收:塑料瓶

我想根据逗号将它们分成不同的列,如下所示:

Garbage Organics Recycle Junk
Tissues Milk Cardboards Null
Paper Towels Eggs Glass Feces
Cups Null Plastic bottles Null

我试过使用 Lambda 函数,但它仅在逗号分隔字符串长度相同但长度不等且显示索引错误“列表索引超出范围”时有效。我使用的代码如下:

list_of_dicts = [{x1.split(':')[0].strip():x1.split(':')[1].strip() for x1 in x.split(',')} for x in Df1['column_name']]
Df2=pd.DataFrame.from_dict(list_of_dicts)

非常感谢任何帮助。谢谢

我们可以使用正则表达式模式从 column_A 的每一行中找到所有匹配的键值对,然后 map 从每一行到字典的键值对列表以创建记录然后从这些记录构建一个数据框

pd.DataFrame(map(dict, df['column_A'].str.findall(r'\s*([^:,]+):\s*([^,]+)')))

在线查看regex demo

        Garbage Organics          Recycle   Junk
0       Tissues     Milk       Cardboards    NaN
1  Paper Towels     Eggs            Glass  Feces
2          cups      NaN  Plastic bottles    NaN

如果您不想使用正则表达式模式,这里有一个替代方法

df['column_A'].str.split(', ').explode()\
              .str.split(': ', expand=True)\
              .set_index(0, append=True)[1].unstack()