How to group a Series by values in pandas?

后端 未结 5 1881
悲&欢浪女
悲&欢浪女 2021-02-01 00:31

I currently have a pandas Series with dtype Timestamp, and I want to group it by date (and have many rows with different times in each group).

相关标签:
5条回答
  • 2021-02-01 00:55

    Three methods:

    DataFrame: pd.groupby(['column']).size()

    Series: sel.groupby(sel).size()

    Series to DataFrame:

    pd.DataFrame( sel, columns=['column']).groupby(['column']).size()

    0 讨论(0)
  • 2021-02-01 01:00

    You should convert it to a DataFrame, then add a column that is the date(). You can do groupby on the DataFrame with the date column.

    df = pandas.DataFrame(s, columns=["datetime"])
    df["date"] = df["datetime"].apply(lambda x: x.date())
    df.groupby("date")
    

    Then "date" becomes your index. You have to do it this way because the final grouped object needs an index so you can do things like select a group.

    0 讨论(0)
  • 2021-02-01 01:03

    To add another suggestion, I often use the following as it uses simple logic:

    pd.Series(index=s.values).groupby(level=0)
    
    0 讨论(0)
  • 2021-02-01 01:08
    grouped = s.groupby(s)
    

    Or:

    grouped = s.groupby(lambda x: s[x])
    
    0 讨论(0)
  • 2021-02-01 01:14

    For anyone else who wants to do this inline without throwing a lambda in (which tends to kill performance):

    s.to_frame(0).groupby(0)[0]
    
    0 讨论(0)
提交回复
热议问题