【问题标题】:Pandas dataframe group: sum one column, take first element from others熊猫数据框组:对一列求和,从其他列中获取第一个元素
【发布时间】:2018-02-28 10:39:55
【问题描述】:

我有一个熊猫数据框

x = pd.DataFrame.from_dict({'row':[1, 1, 2, 2, 3, 3, 3], 'add': [1, 2, 3, 4, 5, 6, 7], 'take1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'take2': ['11', '22', '33', '44', '55', '66', '77'], 'range': [100, 200, 300, 400, 500, 600, 700]})


   add  range  row take1 take2
0    1    100    1     a    11
1    2    200    1     b    22
2    3    300    2     c    33
3    4    400    2     d    44
4    5    500    3     e    55
5    6    600    3     f    66
6    7    700    3     g    77

我想按row 列对其进行分组,然后在add 列中添加条目,但从take1take2 中获取第一个条目,然后从范围中选择最小值和最大值:

   add    row take1 take2  min_range   max_range
0    3      1     a    11    100        200
1    7      2     c    33    300        400
2    18     3     e    55    500        700

【问题讨论】:

  • 你假设数据总是排序的,或者什么定义了“第一个条目”?
  • 组内索引的第一个条目

标签: python pandas dataframe group-by


【解决方案1】:

通过dict使用DataFrameGroupBy.agg,但随后需要进行一些清理,因为在列中获取MultiIndex

#create a dictionary of column names and functions to apply to that column

d = {'add':'sum', 'take1':'first', 'take2':'first', 'range':['min','max']}

#group by the row column and apply the corresponding aggregation to each 
#column as specified in the dictionary d
df = x.groupby('row', as_index=False).agg(d)

#rename some columns
df = df.rename(columns={'first':'', 'sum':''})
df.columns = ['{0[0]}_{0[1]}'.format(x).strip('_') for x in df.columns] 
print (df)
   row take1  range_min  range_max take2  add
0    1     a        100        200    11    3
1    2     c        300        400    33    7
2    3     e        500        700    55   18

详细信息:根据字典中指定的函数聚合列:

df = x.groupby('row', as_index=False).agg(d)
行范围 take2 take1 add 最小最大第一个总和 0 1 100 200 11 一个 3 1 2 300 400 33 c 7 2 3 500 700 55 e 18

将列名sumfirst 替换为'' 将导致

行范围 take2 take1 add 最小最大 0 1 100 200 11 一个 3 1 2 300 400 33 c 7 2 3 500 700 55 e 18

使用字符串格式化程序对列进行列表理解将获得所需的列名。将其分配给df.columns 将获得所需的输出。

【讨论】:

  • 请看我上面的评论,让我知道您的解决方案是否合规
  • 在 [58] 中也出现此错误:df.columns = df.columns.map(''.join).str.strip('') --- -------------------------------------------------- ---------------------- AttributeError Traceback (最近一次调用最后) in () ----> 1 df.columns = df.columns.map(''.join).str.strip('') AttributeError: 'numpy.ndarray' 对象没有属性 'str
  • 我认为是的,如果认为first 函数总是返回第一个值。不需要排序。
  • 好的,我为它添加另一个解决方案。
  • 你能解释一下你的解决方案吗?每条生产线做什么,生产什么?例如,我很困惑为什么在第一行 df=x.goupby... 之后生成的数据框有 2 行行名,看起来很奇怪。这样我就不用再问类似的问题了:)
【解决方案2】:

这就是我所拥有的,没有列重命名/排序。

x = pd.DataFrame.from_dict({'row':[1, 1, 2, 2, 3, 3, 3], 'add': [1, 2, 3, 4, 5, 6, 7], 'take1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'take2': ['11', '22', '33', '44', '55', '66', '77'], 'range': [100, 200, 300, 400, 500, 600, 700]})
x.reset_index(inplace = True)
min_cols = x.ix[x.groupby(['row'])['index'].idxmin().values][['row','take1','take2']]
x_grouped = x.groupby(['row']).agg({'add':'sum','range':[np.min, np.max]})

x_out = pd.merge(x_grouped,min_cols, how = 'left',left_index = True, right_on = ['row'])

print x_out


   (add, sum)  (range, amin)  (range, amax)  row take1 take2
0           3            100            200    1     a    11
2           7            300            400    2     c    33
4          18            500            700    3     e    55

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 2018-08-12
    • 2020-11-12
    • 2018-05-02
    • 1970-01-01
    • 2017-03-06
    • 2021-02-08
    • 2019-12-02
    • 2021-03-29
    相关资源
    最近更新 更多