使用最简单的索引在python pandas中转置一列

时间:2015-04-29 11:19:50

标签: python pandas transpose

我有以下数据(data_current):

import pandas as pd
import numpy as np

data_current=pd.DataFrame({'medicine':['green tea','fried tomatoes','meditation','meditation'],'disease':['acne','hypertension', 'cancer','lupus']})
data_current

我想要做的是转移其中一个柱子,这样我就可以为每种药物配备一排疾病,而不是多排同一种药物和不同的疾病。保持索引尽可能简单也很重要,即0,1,2 ......即我不想将“药物”指定为索引列,因为我会将其合并到其他键上。 所以,我需要获得data_needed

data_needed=pd.DataFrame({'medicine':['green tea','fried tomatoes','meditation'],'disease_1':['acne','hypertension','cancer'], 'disease_2':['np.nan','np.nan','lupus']})
data_needed

3 个答案:

答案 0 :(得分:5)

我在想你想要一个数据透视表。查看此链接以获取更多信息 - > http://pandas.pydata.org/pandas-docs/stable/reshaping.html

你觉得这个输出可以接受吗?

data_current.pivot(index='medicine', columns='disease', values='disease')

答案 1 :(得分:2)

这是实现输出的一个

首先,在groupbymedicine并获取disease作为列表

In [368]: md = (data_current.groupby('medicine')
                            .apply(lambda x: x['disease'].tolist())
                            .reset_index())

In [369]: md
Out[369]:
         medicine                0
0  fried tomatoes   [hypertension]
1       green tea           [acne]
2      meditation  [cancer, lupus]

然后将列中的列表转换为单独的列

In [370]: dval = pd.DataFrame(md[0].tolist(), )

In [371]: dval
Out[371]:
              0      1
0  hypertension   None
1          acne   None
2        cancer  lupus

现在,您可concat - md dval

In [372]: md = md.drop(0, axis=1)

In [373]: data_final = pd.concat([md, dval], axis=1)

并根据需要重命名列。

In [374]: data_final.columns = ['medicine', 'disease_1', 'disease_2']

In [375]: data_final
Out[375]:
         medicine     disease_1 disease_2
0  fried tomatoes  hypertension      None
1       green tea          acne      None
2      meditation        cancer     lupus

答案 2 :(得分:0)

dc = data_current
dc['disease_header'] = dc.diseases.replace(
                       dict(zip(diseases, 
                                map(lambda v: 'diseases_%d' %v, range(len(diseases))
                           )))

这将给我们:

In [548]: dc
Out[548]: 
        disease        medicine disease_header
0          acne       green tea     diseases_0
1  hypertension  fried tomatoes     diseases_1
2        cancer      meditation     diseases_2
3         lupus      meditation     diseases_3

最后,我们可以转动:

    In [547]: dc.pivot(columns='disease_header', index='medicine', values='disease').reset_index()
Out[547]: 
disease_header        medicine diseases_0    diseases_1 diseases_2 diseases_3
0               fried tomatoes        NaN  hypertension        NaN        NaN
1                    green tea       acne           NaN        NaN        NaN
2                   meditation        NaN           NaN     cancer      lupus