-1

我是 Python 的初学者。为了执行数据挖掘,我想转换一个原始数据集:

PurchaseLine01  PurchaseLine02  PurchaseLine03  PurchaseLine04
milk              egg               sausage  
butter            water      
egg               sugar              cake           water

进入这个数据集:

    milk    egg    sausage  butter  sugar   cake    water
1   TRUE    TRUE    TRUE    FALSE   FALSE   FALSE   FALSE
2   FALSE   FALSE   FALSE   TRUE    FALSE   FALSE   TRUE
3   FALSE   TRUE    FALSE   FALSE   TRUE    TRUE    TRUE

Python中有没有简单的方法来完成这个任务?

4

2 回答 2

0

请使用get_dummies()pandas 的函数来获得预期的输出。

于 2018-05-04T18:06:59.570 回答
0

假设您的数据位于名为df.

import pandas as pd
import numpy as np

cols = np.unique(df.stack().values).tolist() 
new_df = pd.DataFrame(columns=cols, index=range(len(df))) 

def get_series(string): 
    return (df == string).T.any() 

for col in cols: 
    new_df[col] = get_series(col) 
new_df
于 2018-06-14T04:05:39.220 回答