【发布时间】:2019-12-11 09:48:43
【问题描述】:
在给定数据框中其他两列的唯一值的情况下,我需要找到一列的总和。
模拟我正在尝试做的示例代码。
import numpy as np
import pandas as pd
def makeDictArray(**kwargs):
data = {}
size = kwargs.get('size',20)
strings = 'What is this sentence about? And why do you care?'.split(' ')
bools = [True,False]
bytestrings = list(map(lambda x:bytes(x,encoding='utf-8'),strings))
data['ByteString'] = np.random.choice(bytestrings, size)
data['Unicode'] = np.random.choice(strings, size)
data['Integer'] = np.random.randint(0,500,size)
data['Float'] = np.random.random(size)
data['Bool'] = np.random.choice(bools,size)
data['Time'] = np.random.randint(0,1500,size)
return data
def makeDF(**kwargs):
size = kwargs.get('size',20)
data = makeDictArray(size=size)
return pd.DataFrame(data)
x = makeDF(size=1000000)
x['SUM'] = 0.
xx = x.groupby(['Time','Integer'])['Float'].agg('sum')
这里是xx:
Time Integer
0 0 0.826326
1 4.897836
2 5.238863
3 6.694214
4 6.791922
1499 495 5.621809
496 7.385356
497 4.755907
498 6.470006
499 3.634070
Name: Float, Length: 749742, dtype: float64
我尝试过的:
uniqueTimes = pd.unique(x['Time'])
for t in uniqueTimes:
for i in xx[t].index:
idx = (x['Time'] == t) & (x['Integer'] == i)
if idx.any():
x.loc[idx,'SUM'] = xx[t][i]
这给了我正确的结果,但我想将总和的值放回新创建的“SUM”列中的“x”中。我可以通过执行双重 for 循环来实现这一点,但是,这很慢而且似乎不是“熊猫方式”。
大家有什么建议吗?
【问题讨论】:
标签: python pandas dataframe pandas-groupby