gpt4 book ai didi

python - 根据子组计算 Pandas 数据框中每年的出现次数

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:53 28 4
gpt4 key购买 nike

想象一个 pandasdataframe 由

df = pd.DataFrame({
'id': [1, 1, 1, 2, 2],
'location': [1, 2, 3, 1, 2],
'date': [pd.to_datetime('01-01-{}'.format(year)) for year in [2015, 2016, 2015, 2017, 2018]]
}).set_index('id')

看起来像这样

    location       date
id
1 1 2015-01-01
1 2 2016-01-01
1 3 2015-01-01
2 1 2017-01-01
2 2 2018-01-01

现在我想为 date 列中表示的每一年创建一个列,该列按 id 计算出现次数。因此生成的数据框应该是这样的

    location       date  2015  2016  2017  2018
id
1 1 2015-01-01 2 1 0 0
1 2 2016-01-01 2 1 0 0
1 3 2015-01-01 2 1 0 0
2 1 2017-01-01 0 0 1 1
2 2 2018-01-01 0 0 1 1

现在我想象使用 pd.groupby.transform但我想不出最好的解决方案。


我自己的解决方案是

df['year'] = df['date'].map(lambda x: x.year)
df = pd.merge(
df,
pd.pivot_table(df, 'date', 'id', 'year', 'count').fillna(0).astype(int),
left_index=True, right_index=True).drop('year', axis=1)

最佳答案

get_dummies

df.join(pd.get_dummies(df.date.dt.year).sum(level=0))

date location 2015 2016 2017 2018
id
1 2015-01-01 1 2 1 0 0
1 2016-01-01 2 2 1 0 0
1 2015-01-01 3 2 1 0 0
2 2017-01-01 1 0 0 1 1
2 2018-01-01 2 0 0 1 1

分解

i, r = pd.factorize(df.index)
j, c = pd.factorize(df.date.dt.year)
n, m = shape = len(r), len(c)
b = np.zeros(shape, dtype=np.int64)
np.add.at(b, (i, j), 1)

df.join(pd.DataFrame(b, r, c).rename_axis('id'))

date location 2015 2016 2017 2018
id
1 2015-01-01 1 2 1 0 0
1 2016-01-01 2 2 1 0 0
1 2015-01-01 3 2 1 0 0
2 2017-01-01 1 0 0 1 1
2 2018-01-01 2 0 0 1 1

关于python - 根据子组计算 Pandas 数据框中每年的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52256120/

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