3

タイムスタンプが一意でない場合、Pandas DataFrame で日付ごとに観測をカウントする最良の方法は何ですか?

df = pd.DataFrame({'User' : ['A', 'B', 'C'] * 40,
                   'Value' : np.random.randn(120),
                   'Time' : [np.random.choice(pd.date_range(datetime.datetime(2013,1,1,0,0,0),datetime.datetime(2013,1,3,0,0,0),freq='H')) for i in range(120)]})

理想的には、出力は 1 日あたりの観測数 (または他の高次の時間単位) を提供します。これを使用して、時間の経過に伴うアクティビティをプロットできます。

2013-01-01     60
2013-01-02     60
4

3 に答える 3

3

これを行う「非パンダ的」な方法は、日付に変換された一連の datetime で Counter オブジェクトを使用し、このカウンターを一連に変換し、この一連のインデックスを datetimes に強制することです。

In[1]:  from collections import Counter
In[2]:  counted_dates = Counter(df['Time'].apply(lambda x: x.date()))
In[3]:  counted_series = pd.Series(counted_dates)
In[4]:  counted_series.index = pd.to_datetime(counted_series.index)
In[5]:  counted_series
Out[5]:
2013-01-01     60
2013-01-02     60

より「パンダ的な」方法は、シリーズで groupby 操作を使用し、出力を長さで集計することです。

In[1]:  grouped_dates = df.groupby(df['Time'].apply(lambda x : x.date()))
In[2]:  grouped_dates['Time'].aggregate(len)
Out[2]:  
2013-01-01     60
2013-01-02     60

編集:ここから借りた別の非常に簡潔な可能性は、nuniqueクラスを使用することです:

In[1]:  df.groupby(df['Time'].apply(lambda x : x.date())).agg({'Time':pd.Series.nunique})
Out[1]:  
2013-01-01     60
2013-01-02     60

スタイルの違いに加えて、一方が他方よりも大きなパフォーマンス上の利点を持っていますか? 私が見落としている他の組み込みメソッドはありますか?

于 2014-01-24T22:08:58.503 に答える