![](/img/trans.png)
[英]How do I get count of each value from a pandas Data Frame column if the column elements is a set?
[英]Change pandas data frame to add max column -> maximum value for each month of the year from a data frame in pandas. How can I do this?
所以我有一個數據框結構,看起來像 (Date, value, month, year) <- 從數據框中提取月份和年份。 我想在一年中的每個月的另一列“max”中獲取“value”列的最大值。 有多個“日期”屬於同一個“月”和“年”。 例如,
Date |value | month | year |
2013-01-03 | 13 | 01 | 2013 |
2013-01-06 | 14 | 01 | 2013 |
2014-01-03 | 16 | 01 | 2014 |
2011-01-03 | 15 | 01 | 2011 |
應該給出類似的東西:
Date |value | month | year | max |
2013-01-03 | 13 | 01 | 2013 | 14 |
2013-01-06 | 14 | 01 | 2013 | 14 |
2014-01-03 | 16 | 01 | 2014 | 16 |
2011-01-03 | 15 | 01 | 2011 | 15 |
使用pd.Grouper
分組並transform
:
df["Date"] = pd.to_datetime(df["Date"])
df["max"] = df.groupby(pd.Grouper(key="Date", freq="M"))["value"].transform("max")
# or df.groupby(df["Date"].str[:8])["value"].transform("max")
print (df)
Date value month year max
0 2013-01-03 13 1 2013 14
1 2013-01-06 14 1 2013 14
2 2014-01-03 16 1 2014 16
3 2011-01-03 15 1 2011 15
嘗試這個
df['max'] = df.apply(lambda r: df[(df.month==r['month']) & (df.year==r['year'])]['value'].max(), axis=1)
我假設Date列是datetime類型。
利用:
df['Max'] = df.groupby(pd.Grouper(key='Date', freq='M')).value.transform(max)
我故意將列名更改為Max (以大寫M開頭),以免“覆蓋”現有的Pandas function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.