我有一个数据框,我将其分组如下并将某些操作应用于特定列:
df = df.groupby(['A', 'B', 'C']).agg({'ID': 'count', 'AMT': 'sum'})
对于每个 groupby 组合 (~15),我想对属于每个组合的行进行随机采样,并返回样本 ID 并在第三个输出列中报告它。或者我真的只是希望该组合中的行中的 ID 之一出现在表中,我不在乎它是否是“随机”。
我尝试过以下方法:
df = df.groupby(['A', 'B', 'C']).agg({'ID': 'count', 'AMT': 'sum', 'ID': 'sample'})
并收到错误:
AttributeError: Cannot access callable attribute 'sample' of 'SeriesGroupBy' objects, try using the 'apply' method
所以我尝试了:
func = lambda x: x.sample
df = df.groupby(['A', 'B', 'C']).agg({'ID': 'count', 'AMT': 'sum', 'ID': apply(func)})
这不起作用,所以我尝试了
df = df.groupby(['A', 'B', 'C']).agg({'ID': 'count', 'AMT': 'sum', 'ID': lambda x: x.sample})
这也不起作用。我已查看以下相关问题的链接,但它们似乎也没有帮助我。
Select multiple groups from pandas groupby object
http://pandas.pydata.org/pandas-docs/stable/groupby.html
Get specific element from Groups after applying groupby - PANDAS
How to access pandas groupby dataframe by key
https://chrisalbon.com/python/pandas_apply_operations_to_dataframes.html
关于如何处理有什么想法吗?
最佳答案
您尝试使用的代码存在一些问题。
lambda x: x.sample
返回函数本身,而不是调用它(dolambda x: x.sample()
)。x.sample()
返回一个Series
对象。.agg()
排除单个标量值或列表,因此会导致异常。您可以执行 x.sample().tolist() 操作,但现在您拥有一个列表而不是单个值。这里使用numpy.random.choice()
更方便。- 在传递给
.agg()
的字典中多次指定同一列不起作用。只有最后一个会坚持下去。将您想要用作列表或字典的函数分配给该列。
考虑到上述情况,您将得到以下解决方案:
import numpy as np
df = df.groupby(['A', 'B', 'C']).agg({'ID': ('count', np.random.choice), 'AMT': 'sum'})
关于python - 按列对分组数据框进行采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43056021/