数据转换/准备
Data Transformation / Preparation
我是 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有没有简单的方法来完成这个任务?
请使用 pandas 中的 get_dummies()
函数以获得预期输出。
假设您的数据位于名为 df
的 DataFrame 中。
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
我是 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有没有简单的方法来完成这个任务?
请使用 pandas 中的 get_dummies()
函数以获得预期输出。
假设您的数据位于名为 df
的 DataFrame 中。
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