给定此数据框:
data = [['Tom', 'run', '2022-01-26', 'run', '2027-01-26'], ['Max', 'stop', '2020-11-16', 'run', '2022-04-26'], ['Bob', 'run', '2021-10-03', 'stop', '2022-01-26'], ['Ben', 'run', '2020-03-11', 'stop', '2013-01-26'], ['Eva', 'stop', '2017-11-16', 'run', '2015-01-26']]
df = pd.DataFrame(data, columns=['person', 'action_1', 'time_1', 'action_2', 'time_2'])
person action_1 time_1 action_2 time_2
0 Tom run 2022-01-26 run 2027-01-26
1 Max stop 2020-11-16 run 2022-04-26
2 Bob run 2021-10-03 stop 2022-01-26
3 Ben run 2020-03-11 stop 2013-01-26
4 Eva stop 2017-11-16 run 2015-01-26
我希望它看起来像:
person action time
0 Tom run 2022-01-26
1 Max stop 2020-11-16
2 Bob run 2021-10-03
3 Ben run 2020-03-11
4 Eva stop 2017-11-16
5 Tom run 2027-01-26
6 Max run 2022-04-26
7 Bob stop 2022-01-26
8 Ben stop 2013-01-26
9 Eva run 2015-01-26
2条答案
按热度按时间ttp71kqs1#
这可以通过
pd.wide_to_long
来实现:输出:
rjzwgtxy2#
pyjanitor中pivot_longger的一个选项-它可以处理非唯一索引:
另一个选项,使用
.value
: