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

标签 python pandas

小代码是...

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)

我当前数据帧的输出...

   date       animals       quantity
0  2015-02-10    dogs       1
1  2015-02-11    cats       2
2  2015-02-11    pigs       5

我希望它看起来像什么......

   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

非常感谢您的帮助。

最佳答案

从您的数据框开始:

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

您可以使用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

除了“动物”和“数量”列之外,这将为您提供所需的输出。他们需要在那里吗?

关于Python - 如何根据现有列中具有相应值的唯一值在数据框中创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28436975/

相关文章:

python - 每个用户每个产品的 session 持续时间

python - 将 Pandas 数据框中的每一行复制到单个文件

python - 尝试使用 Deque 来限制传入数据的 DataFrame ......建议?

python - Pandas :一个系列的真值是模棱两可的

python - 皮图/Matplotlib : How to access figures opened by another interpreter?

python - HDF5 文件内的损坏节点

python - 如果找不到文件,则引发ValueError

python - 在 pandas python 数据框中移动上面的列并删除行

python - 导入文本文件 : No Columns to parse from file

python - 如何使用 Open3D 创建带有点云更新的基本 GUI?