考虑以下数据帧:
A B C D
0 foo one 0.162003 0.087469
1 bar one -1.156319 -1.526272
2 foo two 0.833892 -1.666304
3 bar three -2.026673 -0.322057
4 foo two 0.411452 -0.954371
5 bar two 0.765878 -0.095968
6 foo one -0.654890 0.678091
7 foo three -1.789842 -1.130922
Run Code Online (Sandbox Code Playgroud)
以下命令有效:
> df.groupby('A').apply(lambda x: (x['C'] - x['D']))
> df.groupby('A').apply(lambda x: (x['C'] - x['D']).mean())
Run Code Online (Sandbox Code Playgroud)
但没有以下工作:
> df.groupby('A').transform(lambda x: (x['C'] - x['D']))
ValueError: could not broadcast input array from shape (5) into shape (5,3)
> df.groupby('A').transform(lambda x: …Run Code Online (Sandbox Code Playgroud) 我有:
df = pd.DataFrame({'A':[1, 2, -3],'B':[1,2,6]})
df
A B
0 1 1
1 2 2
2 -3 6
Run Code Online (Sandbox Code Playgroud)
问:我如何获得:
A
0 1
1 2
2 1.5
Run Code Online (Sandbox Code Playgroud)
使用groupby()和aggregate()?
就像是,
df.groupby([0,1], axis=1).aggregate('mean')
Run Code Online (Sandbox Code Playgroud)
所以基本上是 groupby 并axis=1使用行索引0和1进行分组。(不使用转置)
我对Python世界相对较新,并试图将其用作进行数据分析的备份平台.我通常data.table用于我的数据分析需求.
问题是,当我在大型CSV文件上运行group-aggregate操作(随机,压缩,上传到http://www.filedropper.com/ddataredact_1)时,Python抛出:
分组pandas返回getattr(obj,方法)(*args,**kwds)ValueError:不允许负尺寸
或者(我甚至遇到过......)
文件"C:\ Anaconda3\lib\site-packages\pandas\core\reshape\util.py",第65行,在cartesian_product中为i,x在枚举(X)中文件"C:\ Anaconda3\lib\site- packages\pandas\core\reshape\util.py",第65行,in为i,x为枚举(X)]文件"C:\ Anaconda3\lib\site-packages \numpy\core\fromnumeric.py",line 445,重复返回_wrapfunc(a,'repeat',重复,轴=轴)文件"C:\ Anaconda3\lib\site-packages \numpy\core\fromnumeric.py",第51行,在_wrapfunc中返回getattr(obj ,方法)(*args,**kwds)MemoryError
我花了三天时间尝试减小文件大小(我能够将大小缩小89%),添加断点,调试它,但我无法取得任何进展.
令人惊讶的是,我想data.table在R 中运行相同的组/聚合操作,并且它几乎不需要1秒钟.此外,我没有做任何数据类型转换等,建议在https://www.dataquest.io/blog/pandas-big-data/.
我还研究了其他线程:避免大型Pandas DataFrame上的GroupBy的内存问题,Pandas:df.groupby()对于大数据集来说太慢了.任何替代方法?,和pandas groupby与大csv文件上的sum()?.似乎这些线程更多的是关于矩阵乘法.如果您不将此标记为重复,我将不胜感激.
这是我的Python代码:
finaldatapath = "..\Data_R"
ddata = pd.read_csv(finaldatapath +"\\"+"ddata_redact.csv", low_memory=False,encoding ="ISO-8859-1")
#before optimization: 353MB
ddata.info(memory_usage="deep")
#optimize file: Object-types are the biggest culprit.
ddata_obj = ddata.select_dtypes(include=['object']).copy()
#Now convert this to category type:
#Float type didn't help much, so I am excluding it here.
for col in ddata_obj:
del …Run Code Online (Sandbox Code Playgroud) 如果我只是传递一个函数,那么DataFrame.aggregate()和DataFrame.apply()函数之间的返回值的(类型)有什么不同吗?
func=lambda x: x**2
Run Code Online (Sandbox Code Playgroud)
因为返回值似乎非常相似.文档只告诉:
apply() - > applied:Series或DataFrame
aggregate() - > aggregated:DataFrame
在常见的使用模式中,我需要使用自定义聚合函数聚合DataFrame.在这种特殊情况下,聚合函数需要知道当前组才能正确执行聚合.
DataFrameGroupBy.aggregate()为每个组和每个列调用传递给的函数,接收具有当前组和列中元素的Series.我发现从聚合函数中获取组名的唯一方法是将分组列添加到索引,然后使用提取值
x.index.get_level_values('power')[0].这是一个例子:
def _tail_mean_user_th(x):
power = x.index.get_level_values('power')[0]
th = th_dict[power] # this values changes with the group
return x.loc[x > th].mean() - th
mbsize_df = (bursts_sel.set_index('power', append=True).groupby('power')
.agg({'nt': _tail_mean_user_th}))
Run Code Online (Sandbox Code Playgroud)
在我看来,聚合函数需要知道当前组是很常见的事情.在这种情况下是否有更直接的模式?
编辑:我在下面接受的解决方案包括使用apply而不是agg在GroupBy对象上.两者之间的区别在于,分别agg为每个组和每个列apply调用函数,同时为每个组调用函数(所有列一次调用).这样做的一个微妙结果是,agg它将传递一个Series当前组和列,其name属性等于原始列名.相反,apply将Series使用name等于当前组的属性传递a (这是我的问题).有趣的是,当在多个列上操作时,apply将传递一个DataFrame,其中包含name设置为组名的属性(对于DataFrames通常不存在).因此,这种模式在一次聚合多个列时也有效.
有关更多信息,请参阅pandas agg和apply函数之间的区别是什么?