我希望以下面的每日形式输出(下面是示例,我想将第1行的数据转换为Daily,然后将第2行和…(日期范围未确定)转换为:
首先,我只想问专家关于python中这种数据处理的可能性。我正在尝试以下代码:
# data1 = dataframe name
data1['Daily']=(data1['Total Spot']/((data1['Event End']-data1['Event Start']).dt.days)+1)
for date in data1:
pd.date_range(data1['Event Start'], data1['Event End'],freq='D')
我应该在上面的代码中包括什么以获得理想的输出?
答案 0 :(得分:1)
您可以对新的DataFrame
和随后的1.0以及原始数据使用列表推导和平坦化:
data1 = pd.DataFrame({'Event Start':['03/28/2018','04/02/2018'],
'Event End':['04/03/2018','04/05/2018'],
'Team 1':['AAB','AAC'],
'Team 2':['BBB','ABC'],
'Total Spot':[160, 350]})
c = ['Event Start','Event End']
data1[c] = data1[c].apply(pd.to_datetime)
data1['Daily']=(data1['Total Spot']/((data1['Event End']-data1['Event Start']).dt.days)+1)
print (data1)
Event Start Event End Team 1 Team 2 Total Spot Daily
0 2018-03-28 2018-04-03 AAB BBB 160 27.666667
1 2018-04-02 2018-04-05 AAC ABC 350 117.666667
L = [(i, x) for i, s, e in zip(data1.index, data1['Event Start'], data1['Event End'])
for x in pd.date_range(s, e)]
df = (pd.DataFrame(L, columns=['idx','Day'])
.merge(data1.drop(c + ['Total Spot'], axis=1), left_on='idx', right_index=True)
.drop('idx', axis=1))
print (df)
Day Team 1 Team 2 Daily
0 2018-03-28 AAB BBB 27.666667
1 2018-03-29 AAB BBB 27.666667
2 2018-03-30 AAB BBB 27.666667
3 2018-03-31 AAB BBB 27.666667
4 2018-04-01 AAB BBB 27.666667
5 2018-04-02 AAB BBB 27.666667
6 2018-04-03 AAB BBB 27.666667
7 2018-04-02 AAC ABC 117.666667
8 2018-04-03 AAC ABC 117.666667
9 2018-04-04 AAC ABC 117.666667
10 2018-04-05 AAC ABC 117.666667
另一个类似的解决方案:
zipped = zip(data1['Team 1'], data1['Team 2'],
data1['Daily'], data1['Event Start'], data1['Event End'])
L = [(x, t1, t2, d) for t1, t2, d, s, e in zipped for x in pd.date_range(s, e)]
print (L)
df = pd.DataFrame(L, columns=['Day', 'Team 1','Team 2','Daily'])
print (df)
Day Team 1 Team 2 Daily
0 2018-03-28 AAB BBB 27.666667
1 2018-03-29 AAB BBB 27.666667
2 2018-03-30 AAB BBB 27.666667
3 2018-03-31 AAB BBB 27.666667
4 2018-04-01 AAB BBB 27.666667
5 2018-04-02 AAB BBB 27.666667
6 2018-04-03 AAB BBB 27.666667
7 2018-04-02 AAC ABC 117.666667
8 2018-04-03 AAC ABC 117.666667
9 2018-04-04 AAC ABC 117.666667
10 2018-04-05 AAC ABC 117.666667