Skip to main content
 首页 » 编程设计

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

2025年05月04日13xing901022

我有以下数据(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 

请您参考如下方法:

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

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

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