pandas |从列到二进制列的列表

2024-09-28 21:27:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

+------------+------------------+
| item       | categories       |
+------------+------------------+
| blue_shirt | ['red', 'white'] |
+------------+------------------+
| red_skirt  | ['blue', 'red']  |
+------------+------------------+

我想换成这个:

+------------+-----+-------+------+
| item       | red | white | blue |
+------------+-----+-------+------+
| blue_shirt | 1   | 1     | 0    |
+------------+-----+-------+------+
| red_skirt  | 1   | 0     | 1    |
+------------+-----+-------+------+

以下是我尝试过的:

orders = orders.join(pd.get_dummies(orders['Categories'].explode()))

它创建了正确的列,但也创建了(很多)额外的行。我希望每个项目的末尾都有一行,就像上面的例子一样


Tags: 数据getbluereditempdcategorieswhite
2条回答

您可以分解数据帧中的类别和轴:

print(
    df.explode("categories")
    .pivot_table(
        index="item", columns="categories", aggfunc="size", fill_value=0
    )
    .reset_index()
)

印刷品:

categories        item  blue  red  white
0           blue_shirt     0    1      1
1            red_skirt     1    1      0

我能够通过以下方法获得您想要的结果

步骤1:创建将在结果数据集中使用的列列表

>>> cols = list(set(df['categories'].explode())) #set makes sure we keep unique columns
>>> cols.insert(0,df.columns[0]) 

cols
Out[359]: ['item', 'red', 'white', 'blue']

可选:您可以通过将列转换为列表类型来确保explode()有效:taken from here

from ast import literal_eval
df['categories'] = df['categories'].apply(literal_eval) # convert to list type

步骤2:将代码与pd.get_dummies()一起使用,并创建1/0数据集。为了避免获得更多的行,我使用groupby.index添加了一个额外的步骤:

>>> temp = pd.get_dummies(df['categories'].explode())
>>> temp_res = temp.groupby(temp.index).sum()

Out[365]: 
   blue  red  white
0     0    1      1
1     1    1      0

第3步:,Iconcat您的“项目”列具有上述结果,并使用在第一步中创建的列列表获得所需的结果:

>>> out = pd.concat([df['item'],temp_res],axis=1,ignore_index=False)
>>> out = out[cols]

Out[368]: 
         item  red  white  blue
0  blue_shirt    1      1     0
1   red_skirt    1      0     1

一个块中的所有代码

from ast import literal_eval
df['categories'] = df['categories'].apply(literal_eval) #convert to list type

cols = list(set(df['categories'].explode()))
cols.insert(0,df.columns[0]) 

temp = pd.get_dummies(df['categories'].explode())
temp_res = temp.groupby(temp.index).sum()

out = pd.concat([df['item'],temp_res],axis=1)
out = out[cols]

相关问题 更多 >