簡體   English   中英

遍歷 pandas 數據幀或 groupby object

[英]Iterate over a pandas data frame or groupby object

df_headlines =

https://i.imgur.com/OnLfhQ5.png

我想按date列分組,然后計算-101按日期出現的次數,然后以計數最高的為准,將其用作daily_score

我從groupby開始:

df_group = df_headlines.groupby('date')

這將返回一個 groupby object ,鑒於我想在上面做的事情,我不確定如何使用它:

https://i.imgur.com/jmTcrNG.png

我可以使用以下方法進行迭代嗎?:

for index, row in df_group.iterrows():
    daily_pos = []
    daily_neg = []
    daily_neu = []

正如 Ch3steR 作為評論所暗示的那樣,您可以通過以下方式遍歷您的組:

for name, group in headlines.groupby('date'):
    daily_pos = len(group[group['score'] == 1])
    daily_neg = len(group[group['score'] == -1])
    daily_neu = len(group[group['score'] == 0])

print(name, daily_pos, daily_neg, daily_neu)

對於每次迭代,變量name將包含來自date列的值(例如 4/13/20、4/14/20、5/13/20),變量group將包含日期的所有行的date包含在name變量中。

嘗試:

df_headlines.groupby("date")["score"].nlargest(1).reset_index(level=1, drop=True)

無需循環 - 您將在每組中獲得最常見的score

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM