简体   繁体   English

根据单元格内容组合来自不同行的数据并基于单元格值创建新列 pandas 和 python

[英]Combining data from different rows based on the cell content and creating new columns based on the cell values with pandas and python

I have data in csv file where in every row there's a name, a fruit and amount related to the fruit.我在 csv 文件中有数据,其中每一行都有一个名称、一个水果和与水果相关的数量。 What i want is to combine the data from different rows to a single row where all amounts for fruits related to a certain name is under one row.我想要的是将来自不同行的数据组合到一行中,其中与某个名称相关的水果的所有数量都在一行之下。

I have trouble finding a proper way of reading all the data from the fruit column and converting those fruit values to individual rows.我很难找到从水果列中读取所有数据并将这些水果值转换为单独行的正确方法。

Also the null values has to be converted to zero (but that might be quite easy to do). null 值也必须转换为零(但这可能很容易做到)。

I'm using python and pandas dataframe, but i'm quite new to coding and pandas so i'm not that familiar doing this.我正在使用 python 和 pandas dataframe,但我对编码很陌生,而 Z3A43B4F88325D94022

So this an example of the data I have.所以这是我拥有的数据的一个例子。

name, fruit,     amount
Mike, Banana,    2
Mike, Kiwi,      3
Anna, Apple,     10
Anna, Banana,    20
Anna, Pineapple, 40
Bert, Pineapple, 100

And this is the format i want it to be:这是我想要的格式:

name, Banana, Kiwi, Apple, Pineapple
Mike, 2,      3,    0,     0
Anna, 20,     0,    10,    40
Bert, 0,      0,    0,     100

Try to use pivot table when you want to reshape a dataframe.当您想要重塑 dataframe 时,请尝试使用 pivot 表。

df.pivot(index='name', columns='fruit', values='amount')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python (pandas) 根据不同行的值创建一个新列 - python (pandas) creating a new column based on values from different rows 将pandas中的数据帧与相同的行和列组合,但不同的单元格值 - Combining dataframes in pandas with the same rows and columns, but different cell values 结合基于熊猫数据框中两列的单元格值 - Combining cell values based on two columns in pandas dataframe 基于python pandas中其他列的值创建新列 - Creating a new column based on values from other columns in python pandas 根据其他列单元格的值设置熊猫DataFrame单元格的内容 - Setting the content of a pandas DataFrame cell based on the values of other columns cells pandas 基于单元格内容和无标题删除行 - pandas drop rows based on cell content and no headers 根据熊猫中的行数据创建新行和新列 - Creating new rows and new columns based on row data in pandas pandas df select 列基于单元格值 - pandas df select columns based on cell values 根据不同行值的差异在 Pandas 中创建新列 - Creating new columns in Pandas based on difference of different row values 根据其他行和列的多个条件在数据框中创建新列? 包括空行? - 蟒蛇/熊猫 - Creating a new column in dataframe based on multiple conditions from other rows and columns? Including rows that are null? - Python/Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM