Python-如何从现有列的唯一值和对应值创建数据框中的新列? [英] Python - how to create new columns in a dataframe from the unique values from an existing column with corresponding values?

查看:114
本文介绍了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)

当前数据帧的输出...

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

我将很感谢您的帮助.

推荐答案

从数据框开始:

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方法指定应将哪些列用作索引,列名称和值:

You can use the pivot method specifying which columns should be used as the index, as the column names, and as the values:

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?

这篇关于Python-如何从现有列的唯一值和对应值创建数据框中的新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆