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

I have the following data (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

What I would like to do is to transpose one of the columns, so that instead of having multiple rows with same medicine and different diseases I have one row for each medicine with several columns for diseases. It is also important to keep index as simple as possible, i.e. 0,1,2... i.e. I don't want to assign 'medicines' as index column because I will merge it on some other key.

So, I need to get 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

解决方案

Here's one to achieve the output

Firstly, groupby on medicine and get the disease as list

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]

Then convert the lists in column to separate columns

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

In [371]: dval

Out[371]:

0 1

0 hypertension None

1 acne None

2 cancer lupus

Now, you can concat -- md with dval

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

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

And, rename the columns as you want.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值