python - 使用多个数据框创建 pandas 数据框

标签 python pandas csv

我有一个像这样的 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/

相关文章:

python - 在 Python 中选择长度为 n 的随机列表元素

python - Django 1.8 不使用我的自定义登录页面

Python:具有多个条件的 np.where

java - 如何读取csv文件中的指定行

python - 修复混合编码的 csv 中的编码错误

python - 如何在 qcut 之后在分类变量中添加新类别?

python - 保留 FuncAnimation 帧之间的轴设置

python - 如何在 Python 中过滤对象数组?

python - Pandas 数据框从长到宽转换,每个索引的行数不同

node.js - 将 UTF-8 csv 文件转换为 Excel 可读的 csv