簡體   English   中英

如何使用pandas計算數據框中每個日期的值?

[英]How can I use pandas to count values for each date in a dataframe?

我是python中pandas庫的新手,我一直試圖拼湊如何獲取像這樣的數據幀

    'Date'  'Color'
0   '05-10-2017'    'Red'
1   '05-10-2017'    'Green'
2   '05-10-2017'    'Blue'
3   '05-10-2017'    'Red'
4   '05-10-2017'    'Blue'
5   '05-11-2017'    'Red'
6   '05-11-2017'    'Green'
7   '05-11-2017'    'Red'
8   '05-11-2017'    'Green'
9   '05-11-2017'    'Blue'
10  '05-11-2017'    'Blue'
11  '05-11-2017'    'Red'
12  '05-11-2017'    'Blue'
13  '05-11-2017'    'Blue'
14  '05-12-2017'    'Green'
15  '05-12-2017'    'Blue'
16  '05-12-2017'    'Red'
17  '05-12-2017'    'Blue'
18  '05-12-2017'    'Blue'

並輸出一個具有唯一日期作為索引,顏色作為列標題,每天的值計數如下:

'Date'       'Red' 'Green' 'Blue'
'05-10-2017'     2       1      2 
'05-11-2017'     3       2      3
'05-12-2017'     1       1      3

過去兩天我一直在努力搜索這個網站,試圖拼湊出一種實現這一目標的方法,到目前為止我只能生成獨特日期的索引。 我在使用value_counts時遇到了一些麻煩。 如果有人能夠向我展示一種方法,或者如果已經回答了這個方法,我會很感激。 我已經用盡了我的搜索能力,終於決定在這里問我的第一個問題。 如果我是個白痴,請保持溫柔。

您可以使用:

1。

groupby + size為aggregting和unstack的重塑:

df1 = df.groupby(["'Date'","'Color'"]).size().unstack(fill_value=0)
print (df1)
'Color'       'Blue'  'Green'  'Red'
'Date'                              
'05-10-2017'       2        1      2
'05-11-2017'       4        2      3
'05-12-2017'       3        1      1

2。

pivot_table解決方案:

df1 = df.pivot_table(index="'Date'",columns="'Color'", aggfunc='size')
print (df1)
'Color'       'Blue'  'Green'  'Red'
'Date'                              
'05-10-2017'       2        1      2
'05-11-2017'       4        2      3
'05-12-2017'       3        1      1

3。

crosstab解決方案,更慢:

df1 = pd.crosstab(df["'Date'"],df["'Color'"])
print (df1)
'Color'       'Blue'  'Green'  'Red'
'Date'                              
'05-10-2017'       2        1      2
'05-11-2017'       4        2      3
'05-12-2017'       3        1      1

暫無
暫無

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

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