gpt4 book ai didi

python - 你如何拆开 DataFrame 中的列?

转载 作者:行者123 更新时间:2023-11-28 17:56:18 26 4
gpt4 key购买 nike

我有一个 DataFrame,“df”,它有 53 个不同的列和 1740 行。这些列包括; 'Age', 'RaceOne', 'RaceTwo', 'RaceThree', 'Name', 'Identity' .. 等但我想重组 DataFrame 以便用新变量 'RaceTimes' 替换 'RaceOne', 'RaceTwo' , 'RaceThree' 和 DataFrame 列的其余部分以特定方式遵循,如下面的第二个 DataFrame 所示...

当前 df:

'Age'   'RaceOne'   'RaceTwo'   'RaceThree'   'Name'   'Identity'   ...   'Male/Female         
25 15:40:00 15:35:00 15:39:00 Wendy 105888 ... Female
26 15:43:00 15:25:00 15:15:00 Steve 114342 ... Male
22 15:20:00 15:31:00 15:23:00 Ant 123553 ... Male

我想看到的...

'Age'   'RaceTimes'   'Name'   'Identity'   ...   'Male/Female'
25 15:40:00 Wendy 105888 ... Female
25 15:35:00 Wendy 105888 ... Female
25 15:39:00 Wendy 105888 ... Female
26 15:43:00 Steve 114342 ... Male
26 15:25:00 Steve 114342 ... Male
26 15:15:00 Steve 114342 ... Male
22 15:20:00 Ant 123553 ... Male
22 15:31:00 Ant 123553 ... Male
22 15:23:00 Ant 123553 ... Male

最佳答案

IIUC,检查pd.wide_to_long :

final=(pd.wide_to_long(df,'Race',i='Age',j='v',sep='',suffix='\w+').reset_index(1,drop=True)
.sort_index().reset_index())

   Age Male/Female   Name  Identity  ...      Race
0 22 Male Ant 123553 ... 15:20:00
1 22 Male Ant 123553 ... 15:31:00
2 22 Male Ant 123553 ... 15:23:00
3 25 Female Wendy 105888 ... 15:40:00
4 25 Female Wendy 105888 ... 15:35:00
5 25 Female Wendy 105888 ... 15:39:00
6 26 Male Steve 114342 ... 15:43:00
7 26 Male Steve 114342 ... 15:25:00
8 26 Male Steve 114342 ... 15:15:00

关于python - 你如何拆开 DataFrame 中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58109401/

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