【发布时间】:2020-06-25 14:00:43
【问题描述】:
我正在尝试对同一个数据帧执行多个求和,然后将新数据帧连接到一个最终数据帧中。有没有一种简洁的方法,还是我需要使用迭代?
我有一个这种形式的字典 {key: [list_of_idx], ...} 并且需要按我的数据框为每个键分组。
样本数据
import random
random.seed(1)
df_len = 5
df = {'idx':{i: i+1 for i in range(df_len)}, 'data':{i:random.randint(1,11) for i in range(df_len)}}
df = pd.DataFrame(df).set_index('idx')
# Groups with the idx to groupby
groups = {'a': [1,2,3,4,5],
'b': [1,4],
'c': [5]}
# I'm trying to avoid/find a faster way than this
dfs = []
for grp in groups:
_df = df.loc[groups[grp]]
_df['grp'] = grp
_df = _df.groupby('grp').sum()
dfs.append(_df)
dff = pd.concat(dfs)
输入(df)
data idx
0 2 1
1 10 2
2 9 3
3 3 4
4 6 5
预期输出 (dff)
data
grp
a 30
c 6
b 5
注意:我坚持使用 python 2.7 和 pandas 0.16.1
时间结果
我测试了建议的方法并计算了执行时间。我显示了每次执行的平均时间(每个答案使用 1000 次执行): 由于我的 pandas 版本,我无法测试 Quang Hoang 第一个答案。
time method
0.00696 sec my method (question)
0.00328 sec piRSquared (pd.concat)
0.00024 sec piRSquared (collections and defaultdict)
0.00444 sec Quang Hoang (2nd method : concat + reindex)
【问题讨论】:
-
我能说我很惊喜,真的很高兴看到有人遵循一些好的建议,你在这里使用
random.seed(...),这样每个人都可以创建一个可重复的示例,同时仍然能够扩展输入/输出测试:)
标签: python pandas python-2.7 pandas-groupby