我有一個簡單的Pandas
dataframe
其中每行表示一個人和一個日期範圍。對於每個人,我想知道在dataframe
的各個條目中涵蓋硬編碼範圍中的天數百分比(由變量period_start
和定義)。通過Pandas函數計算某個範圍內覆蓋的天數百分比
我認爲有一個簡單的方法可以用Pandas
來做到這一點,但我一直沒有找到。我有一個解決方案與多個dataframes
和幾個嵌套循環,但這是規模效率低下。我怎樣才能更有效地利用Pandas
?我認爲groupby
是合理的,但不知道如何做到這一點,當範圍跨越兩列,並可能重疊。
import pandas as pd
from datetime import datetime
df = pd.DataFrame(data=[['2016-01-01', '2016-01-31', 'A'],
['2016-02-02', '2016-02-10', 'A'],
['2016-03-01', '2016-04-01', 'A'],
['2016-01-01', '2016-03-01', 'B']],
columns=['startdate', 'enddate', 'person'])
# start and end date
period_start = datetime(year=2016, month=01, day=01)
period_end = datetime(year=2016, month=12, day=31)
# dates_dfculate totals days
total_days = (period_end-period_start).days + 1
# convert columns to dates
df['startdate']= pd.to_datetime(df['startdate'], format='%Y-%m-%d')
df['enddate']= pd.to_datetime(df['enddate'], format='%Y-%m-%d')
# create a TimeIndex dataframe with columns for each person
rng = pd.date_range(period_start, periods=total_days, freq='D')
people = list(set(df['person'].tolist()))
dates_df = pd.DataFrame(columns=[people], index=rng).fillna(False)
# loop over each date (index)
for index, row in dates_df.iterrows():
# loop over each column (person)
for person in people:
tmp = df[df['person'] == person]
# loop over each each entry for the person
for index1, row1 in tmp.iterrows():
# check if the date is date index in dates_df is within range
value = row1['startdate'] <= index <= row1['enddate']
# if it's not already set to true, set it to true
if dates_df.ix[index, person] == False and value == True:
dates_df.ix[index, person] = True
# for each person, show the percentage of days in range that are covered
for person in people:
print person, sum(dates_df[person].tolist())/float(total_days)
所需的輸出:
A 0.196721311475
B 0.166666666667
你期望你的期望輸出到***看起來像***? – Abdou
這只是循環播放每個人並打印出百分比。添加輸出到問題。 – user2242044