gpt4 book ai didi

python - 数据框转换

转载 作者:行者123 更新时间:2023-12-01 04:15:23 25 4
gpt4 key购买 nike

我是 Python pandas 的新手,所以这可能是一个愚蠢的问题,pandas 可能有简单的方法来执行此操作

我的数据框如下:

Name        Activity      Date
Abc. Run. June 3
Cde. Walk. Sept. 4
Abc. Run. June 4
Abc. Run. June 5
Code. Walk. June 3
Cde. Run. Sept 5

我想将其转换为

Name  run freq  walk freq 
Abc. 3. 0
Cde. 1. 1
Code. 0. 1

如何在 pandas 中执行此操作?

最佳答案

对列进行分组,获取每个列的计数,然后对结果进行拆分。

df = pd.DataFrame({'Name': ['Abc.', 'Cde.', 'Abc.', 'Abc.', 'Code.', 'Cde.'], 
'Activity': ['Run.', 'Walk.', 'Run.', 'Run.', 'Walk.', 'Run.'],
'Date': ['June 3', 'Sept. 4', 'June 4', 'June 5', 'June 3', 'Sept 5']})

>>> df.groupby(['Name', 'Activity']).count().unstack()

Date
Activity Run. Walk.
Name
Abc. 3 NaN
Cde. 1 1
Code. NaN 1

关于python - 数据框转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362939/

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