Python如何在dataframe中从具有相应值的现有列的唯一值创建新列?

2024-09-28 20:53:33 发布

您现在位置:Python中文网/ 问答频道 /正文

小代码是。。。你知道吗

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

我会很感激你的帮助。你知道吗


Tags: path代码importpandasdateasexcelquantity
1条回答
网友
1楼 · 发布于 2024-09-28 20:53:33

从数据帧开始:

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

除了“animals”和“quantity”列之外,这将获得所需的输出。他们需要在那里吗?你知道吗

相关问题 更多 >