创建具有多个数据框的熊猫数据框

埃里亚斯·科特·阿格洛

我有一个这样的csv文件:

Fruit_Type;Fruit_Color;Fruit_Description
Apple;Green,Red,Yellow;Just an apple
Banana;Green,Yellow;Just a Banana
Orange;Red,Yellow;Just an Orange
Grape;;Just a Grape

(注意:单元格内有逗号,颜色类型编号是可变的,最多可以有三种不同的颜色)

我想要的结果是:

水果类型;水果颜色;水果描述

Apple;Green;0;0;Just an apple
Apple;0;Red;0;Just an apple
Apple;0;0;Yellow;Just an apple
Banana;Green;0;0;Just a Banana
Banana;0;Red;0;Just a Banana
Banana;0;0;Yellow;Just a Banana
Orange;Green;0;0;Just an Orange
Orange;0;Red;0;Just an Orange
Orange;0;0;Yellow;Just an Orange
Grape;0;0;0;Just a Grape
Grape;0;0;0;Just a Grape
Grape;0;0;0;Just a Grape

我想将数据帧Fruit_Color列拆分为3列,这些颜色上的0值不存在。

我试图像这样转换数据框信息数据框以获取包含一些字符串的行:

test.py

#load the csv data into dataframe
data = pd.read_csv(open('test.py','rb'),delimiter=';',encoding='utf-8')

#detect the rows where're the color
Green = data.loc[data['Fruit_Color'].str.contains('Green', case=True)]
Red = data.loc[data['Fruit_Color'].str.contains('Red', case=True)]
Yellow = data.loc[data['Fruit_Color'].str.contains('Yellow', case=True)]

有了这个,我的行中包含特定的颜色,但是我不知道如何用这些数据框制作联接的数据框,我又怎么知道那些行没有像Grape这样的颜色?

提前致谢。

耶斯列尔

我建议使用str.get_dummies

df = df.join(df.pop('Fruit_Color').str.get_dummies(','))
print (df)
  Fruit_Type Fruit_Description  Green  Red  Yellow
0      Apple     Just an apple      1    1       1
1     Banana     Just a Banana      1    0       1
2     Orange    Just an Orange      0    1       1
3      Grape      Just a Grape      0    0       0

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章