考虑以下示例
import numpy as np
import pandas as pd
data = {
'Group': ['A', 'B', 'C', 'D']*3, # Repeating groups to fill the DataFrame
'Timestamp': pd.date_range(start='2023-01-01', periods=12, freq='M'), # Monthly frequency
'Numeric': np.random.rand(12) * 100, # Random numeric values scaled up
'String': ['apple', 'banana', 'cherry', 'date']*3 # Repeating string entries
}
df = pd.DataFrame(data)
df.head()
Out[28]:
Group Timestamp Numeric String
0 A 2023-01-31 69.320654 apple
1 B 2023-02-28 1.667633 banana
2 C 2023-03-31 14.211651 cherry
3 D 2023-04-30 40.061005 date
4 A 2023-05-31 23.433903 apple
我知道我可以使用管道进行链接,效果非常好。但是,以下代码行尝试使用
groupby
过滤 .loc
数据帧失败。这里有什么问题呢?管道不只是传递数据帧吗(所以.loc
应该可以工作)?
(df.groupby('Group')
.pipe(lambda x: x.loc[x.Numeric <4]))
Traceback (most recent call last):
AttributeError: 'DataFrameGroupBy' object has no attribute 'loc'
如果您想对每个组应用一个函数并使结果成为所有结果的串联,请使用
.apply
:
df.groupby('Group').apply(lambda group: group.loc[group.Numeric < 40])
似乎正在做你想做的事。