如何在熊猫中将行拆分为由管道分隔的列

时间:2020-07-31 07:36:21

标签: python pandas

我在熊猫中有以下数据框

data = {'order_id': [123, 221, 234],
        'cust_id': [12, 13, 15],
        'order_total': [2345, 232, 1002],
        'prod_name': ['Chicken wings | Mashroom | Coriander', 'Chicken wings', 'Mashroom | Fish | Garlic']}

order_df = pd.DataFrame(data)

   order_id  cust_id  order_total                             prod_name
0       123       12         2345  Chicken wings | Mashroom | Coriander
1       221       13          232                         Chicken wings
2       234       15         1002              Mashroom | Fish | Garlic

我想要的数据框是

 order_id    cust_id    order_total   Chicken wings   Mashroom   Coriander    Fish    Garlic
 123         12         2345          1               1          1            0       0      
 221         13         232           1               0          0            0       0
 234         15         1002          0               1          0            1       1

我能够将其拆分为不同的产品,但无法生成上述格式。

 split_product_df = order_df.prod_name.str.split("|",expand=True).add_prefix('Product_')

我如何在熊猫中做到这一点。

2 个答案:

答案 0 :(得分:4)

熊猫str dummies为此提供了帮助

@Neil,看来您在|前面有空白,因此请在下面尝试,我们先在空白处搜索|,然后替换它:

pd.concat(
    (df.iloc[:, :-1], df.prod_name.str.replace("\s+(?=\|)", "").str.get_dummies()),
    axis=1,
)

答案 1 :(得分:1)

您可以在索引上使用来自https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html的大熊猫。 分享一个更简单的示例,在这里,如果您的包含字符串的管道具有重复的标签,则以下操作将无效。

import pandas as pd

df = pd.DataFrame({
    'order_id': [123, 456],
    'cust_id': [12, 13],
    'order_total': [2345, 6789],
    'prod_name': ["Chicken wings | Mashroom | Coriander", "Mashroom | Fish | Garlic"]
})


def process(row):
    index = row.name # get the index of row
    for word in row['prod_name'].split('|'):
        # for each word separated by | remove spaces and for that index create a column add count as 1
        w = word.lstrip().rstrip()
        df.loc[index, w] = 1


df.apply(process, axis=1) # apply the process on each row
df.drop('prod_name', axis=1, inplace=True) # drop the prod_name column
df = df.fillna(0) # fill nans with zero