gpt4 book ai didi

python - 在 pandas/python 中转置 DataFrame,但不是所有列

转载 作者:行者123 更新时间:2023-11-28 21:39:30 25 4
gpt4 key购买 nike

我有一个如下所示的 DataFrame。我尝试使用 pivot 转置它,但结果并不如我所愿。我想完成以下 -

df=pd.DataFrame({'ID_Patient':[11132,2755,9753,8453,4872],'Name_Patient':['Jim','Jack','Sue','Tom','James'],'Visits_Jan':[2,1,0,4,2],'Visits_Feb':[5,0,0,1,1],'Visits_Mar':[0,0,4,1,2]})
df=df[['ID_Patient','Name_Patient','Visits_Jan','Visits_Feb','Visits_Mar']]

df#The data set I wish to convert
Out[318]:
ID_Patient Name_Patient Visits_Jan Visits_Feb Visits_Mar
0 11132 Jim 2 5 5
1 2755 Jack 1 0 0
2 9753 Sue 0 0 0
3 8453 Tom 4 1 1
4 4872 James 2 1 1

我想把它转换成:

df_altered
Out[317]:
ID_Patient Name_Patient Month_of_visit Col1
0 11132 Jim Visits_Jan 2
1 11132 Jim Visits_Feb 5
2 11132 Jim Visits_Mar 5
3 2755 Jack Visits_Jan 1
4 2755 Jack Visits_Feb 0
5 2755 Jack Visits_Mar 0
6 9753 Sue Visits_Jan 0
7 9753 Sue Visits_Feb 0
8 9753 Sue Visits_Mar 0
9 8453 Tom Visits_Jan 4
10 8453 Tom Visits_Feb 1
11 8453 Tom Visits_Mar 1
12 4872 James Visits_Jan 2
13 4872 James Visits_Feb 1
14 4872 James Visits_Mar 1

最佳答案

通过使用堆栈

df.set_index(['ID_Patient','Name_Patient']).stack().reset_index()
Out[254]:
ID_Patient Name_Patient level_2 0
0 11132 Jim Visits_Jan 2
1 11132 Jim Visits_Feb 5
2 11132 Jim Visits_Mar 0
3 2755 Jack Visits_Jan 1
4 2755 Jack Visits_Feb 0
5 2755 Jack Visits_Mar 0
6 9753 Sue Visits_Jan 0
7 9753 Sue Visits_Feb 0
8 9753 Sue Visits_Mar 4
9 8453 Tom Visits_Jan 4
10 8453 Tom Visits_Feb 1
11 8453 Tom Visits_Mar 1
12 4872 James Visits_Jan 2
13 4872 James Visits_Feb 1
14 4872 James Visits_Mar 2

PS:使用 .rename(columns={}) 更改列名

关于python - 在 pandas/python 中转置 DataFrame,但不是所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46734037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com