如何将一列的所有项移动到pandas中的列?



我是熊猫新手。我试图将列的项目移动到数据框的列。我挣扎了几个小时,但还是做不到。

<标题>兆瓦h1> 何得到这样的结果:
X  a  b  c  d  e
0  10  1  1  0  1  0
1  20  0  0  0  0  0
2  30  1  1  0  0  0
3  40  1  1  1  0  1
4  50  0  0  0  0  1

MultiLabelBinarizer

from sklearn.preprocessing import MultiLabelBinarizer
mlb = MultiLabelBinarizer()
df[mlb.classes_] = mlb.fit_transform(df['Y'])

熊猫替代

df.join(df['Y'].explode().str.get_dummies().groupby(level=0).max())

X                Y  a  b  c  d  e  f
0  10        [a, b, d]  1  1  0  1  0  0
1  20               []  0  0  0  0  0  0
2  30           [a, b]  1  1  0  0  0  0
3  40  [a, b, e, f, c]  1  1  1  0  1  1
4  50              [e]  0  0  0  0  1  0

您可以试试pandas.Series.str.get_dummies

out = df[['X']].join(df['Y'].apply(','.join).str.get_dummies(sep=','))
print(out)
X  a  b  c  d  e  f
0  10  1  1  0  1  0  0
1  20  0  0  0  0  0  0
2  30  1  1  0  0  0  0
3  40  1  1  1  0  1  1
4  50  0  0  0  0  1  0

我的直接解决方案:检查当前颜色是否在Y列表中,或者添加一个0:

for col in ['a', 'b', 'c', 'd', 'e']:
df[col] = pd.Series([1 if col in df["Y"][x] else 0 for x in range(len(df.index))])
df = df.drop('Y', axis=1)
print(df)

编辑:好的,组比是cleaner

最新更新