[英]Python - how to create new columns in a dataframe from the unique values from an existing column with corresponding values?
small code is... 小代码是...
import pandas as pd
#INPUT FILE INFORMATION
path = 'C:\Users\BDomitz\Desktop\Python\Stack_Example.xlsx'
sheet = "Sheet1"
#READ FILE
dataframe = pd.io.excel.read_excel(path, sheet)
the output for my current dataframe... 我当前数据帧的输出...
date animals quantity
0 2015-02-10 dogs 1
1 2015-02-11 cats 2
2 2015-02-11 pigs 5
what I would like it to look like... 我希望它看起来像什么...
date animals quantity dogs cats pigs
0 2015-02-10 dogs 1 1 0 0
1 2015-02-11 cats, pigs 2 0 2 5
I would appreciate the help. 我会很感激的。
Starting from your dataframe: 从您的数据框开始:
In [9]: df
Out[9]:
date animals quantity
0 2015-02-10 dogs 1
1 2015-02-11 cats 2
2 2015-02-11 pigs 5
You can use the pivot
method specifying which columns should be used as the index, as the column names, and as the values: 您可以使用pivot
方法指定应将哪些列用作索引,列名称和值:
In [10]: df.pivot(index='date', columns='animals', values='quantity').fillna(0)
Out[10]:
animals cats dogs pigs
date
2015-02-10 0 1 0
2015-02-11 2 0 5
This gets you the desired output, apart from the 'animals' and 'quantity' columns. 除了“动物”和“数量”列之外,这还可以为您提供所需的输出。 Are they needed to be there? 他们需要在那里吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.