简体   繁体   English

Python-如何从现有列中的唯一值和相应值创建数据框中的新列?

[英]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.

相关问题 从现有数据框中创建新数据框,其中一列中的唯一值和其他列中的对应值 - Make new dataframe from existing dataframe with unique values from one column and corresponding values from other columns 在由现有列中的值组成的数据框中创建新列 - Create a new column in a dataframe consisting of values from existing columns 通过解析列值为数据框创建新列,并使用来自另一列python的值填充新列 - Create new columns for a dataframe by parsing column values and populate new columns with values from another column python 如何从现有列值创建新列? - How do I create new columns from existing column values? 根据两个现有列的对应值创建一个新列 - Create a new column based on corresponding values of two existing columns 从熊猫数据框中的唯一行值创建新列 - Create new columns from unique row values in a pandas dataframe 创建包含来自现有列的计算值的多个数据框列 - Create multiple dataframe columns containing calculated values from an existing column Pandas:使用从预先存在的列计算的值在数据框中创建两个新列 - Pandas: create two new columns in a dataframe with values calculated from a pre-existing column 从具有不同值和类型的一列创建新的 dataframe 列 - Create new dataframe columns from one column with different values and types 从其他 2 列的值创建新的 dataframe 列 - Create new dataframe column from the values of 2 other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM