我有一个像这样的 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。
我尝试像这样转换数据帧信息数据帧以获取包含某些字符串的行:
测试.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)]
这样,我就有了包含特定颜色的行,但我不知道如何使用这些数据帧创建连接的数据帧,而且我如何知道那些没有像葡萄这样的颜色的行?
提前致谢。
最佳答案
我建议使用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
关于python - 使用多个数据框创建 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49729385/