[英]How to apply a python function to splitted 'from the end' pandas sub-dataframes and get a new dataframe?
[英]Groupby and apply function to sub-dataframes in Python
如何按item
和date
分組,然后對於每個子數據幀,獲取“數據”值是子數據幀中實際中間值的實際行?
有時會有多行data
等於中間值,在這種情況下,我們只保留第一行。
東風:
item date data
0 22 2012-03-10 10
1 22 2012-03-10 20
2 22 2012-03-10 40
3 24 2012-03-11 40
4 24 2012-03-11 50
5 24 2012-03-11 50
預期 output:
1 22 2012-03-10 20
4 24 2012-03-11 50
您可以使用groupby().transform()
然后 boolean 索引:
medians = df.groupby(['item','date'])['data'].transform('median')
# drop duplicates in the case
# there are multiple rows equal to median
df[df['data']==medians].drop_duplicates(['item','date','data'])
Output:
item date data
1 22 2012-03-10 20
4 24 2012-03-11 50
請.groupby()
, . agg(median)
df[['item', 'date', 'data']].groupby(['date', 'item',]).agg('median').reset_index()
date item data
0 2012-03-10 22 20
1 2012-03-11 24 50
您可以使用 pandas df['date'] = pd.to_datetime(df['date']).dt.date 作為示例
df1 = df.groupby(['data','date'])['date','data'].median()
df1
嘗試這個:
df.groupby(['item', 'date'], as_index=False).median()
Output:
item date data
0 22 2012-03-10 20
1 24 2012-03-11 50
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.