数据转换/准备

2024-05-18 11:16:47 发布

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

我是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中有没有一种简单的方法来完成这个任务?你知道吗


Tags: 数据挖掘falsetrue原始数据eggsugarcake初学者
2条回答

请使用pandas的get_dummies()函数获得预期的输出。你知道吗

假设您的数据位于名为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

相关问题 更多 >