![](/img/trans.png)
[英]Get index of the minimum of multi-index Pandas DataFrame using level
[英]In Pandas, how to get the fraction of occurrences in a level of a multi-index?
我有一個帶有兩列的DataFrame
, Type
和Time
:
import pandas as pd
import dateutil.parser
df = pd.DataFrame({'Type' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo', 'foo', 'foo'],
'Time' : ['9:11', '9:54', '15:12', '11:39', '21:50', '15:40', '1:23', '1:48', '9:13', '9:48']})
Type
是指某些分類的事件(此處為foo
和bar
),而Time
是表示一天中的時間的字符串。 我想確定在一天中的哪個小時內foo
比例最高。
到目前為止,我提出了以下建議:
def get_hour(timestring):
return dateutil.parser.parse(timestring).hour
df['_hour'] = df['Time'].apply(get_hour)
grouped_count = df.groupby(['_hour', 'Type']).count()
print(grouped_count)
哪個打印
Time
_hour Type
1 foo 2
9 bar 1
foo 3
11 bar 1
15 bar 1
foo 1
21 foo 1
此處的“ Time
列表示每小時每種類型的總發生次數。 但是,我想生成一個輔助列,即Fraction
,該列具有該小時內每次出現的分數,如下所示:
Time Fraction
_hour Type
1 foo 2 1.0
9 bar 1 0.25
foo 3 0.75
11 bar 1 1.0
15 bar 1 0.5
foo 1 0.5
21 foo 1 1.0
我該如何實現?
您可以按_hour索引進行分組,並使用transform
(或apply
)來計算分數 :
grouped_count['Fraction'] = grouped_count.groupby(level='_hour').Time.transform(lambda x: x/x.sum())
grouped_count
# Time Fraction
#_hour Type
#1 foo 2 1.00
#9 bar 1 0.25
# foo 3 0.75
#11 bar 1 1.00
#15 bar 1 0.50
# foo 1 0.50
#21 foo 1 1.00
如果不需要時間列,也可以執行.value_counts(normalize=True)
:
df.groupby('_hour').Type.value_counts(normalize=True)
#_hour Type
#1 foo 1.00
#9 foo 0.75
# bar 0.25
#11 bar 1.00
#15 bar 0.50
# foo 0.50
#21 foo 1.00
#Name: Type, dtype: float64
使用標准的h:m
字符串,您還可以按以下方式解析hour
:
df.groupby(df.Time.str.extract(r'^(\d+)', expand=False)).Type.value_counts(normalize=True)
采用:
#get hour by splitting to Series h
h = df['Time'].str.split(':').str[0].astype(int).rename('hour')
#for groupby use instead column Series
grouped_count = df.groupby([h, 'Type'])['Time'].count().to_frame()
#divide by aggregate first level hour and sum
grouped_count['Fraction'] = grouped_count.div(grouped_count.sum(level=0))
print(grouped_count)
Time Fraction
hour Type
1 foo 2 1.00
9 bar 1 0.25
foo 3 0.75
11 bar 1 1.00
15 bar 1 0.50
foo 1 0.50
21 foo 1 1.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.