我有一个数据框
import pandas as pd
import datetime
#Create data
df = {'Day': ['2012-12-29','2013-01-05'],
'Whatev': [1,0]}
index = range(len(df['Day']))
columns = ['Day','Whatev']
df = pd.DataFrame(df, index=index, columns=columns)
print(df)
print()
从中我将第一列提取为一系列:
#Index to datetime
df['Day'] = pd.to_datetime(df['Day'])
df.set_index('Day', inplace=True) #use day as index
#Create series from dataframe column
s = df[df.columns[0]]
print(s)
print()
我想在其末尾附加零值。因此,首先我扩展了datetime索引,然后将最后一个值指定为零:
#Append 1 data to series
last_date = s.iloc[[-1]].index + datetime.timedelta(days=7)
s.append(pd.DataFrame(index=[last_date]))
s.iloc[[-1]]=0
print(s)
print()
是的,我没有工作。在测试过程中,它似乎可以正常工作,但是在某种程度上,数据框未更改。是什么原因
另外,有没有更聪明的方法来达到目的?实际上,如果我想附加多个值,我的解决方案看起来会很糟糕:
#Append many data to series
L = 2 #hoe many zeros
i=0
while i<=L:
i+=1
last_date = s.iloc[[-1]].index + datetime.timedelta(days=7)
s.append(pd.DataFrame(index=[last_date]))
s.iloc[[-1]]=0
print(s)
您可以使用setting-with-enlargement
以下代码简化代码:
df['Day'] = pd.to_datetime(df['Day'])
s = df.set_index('Day')['Whatev']
循环版本:
L = 2 #hoe many zeros
i=0
while i<=L:
i+=1
last_date = s.index[-1] + pd.Timedelta(days=7)
s.loc[last_date]=0
print(s)
2012-12-29 1
2013-01-05 0
2013-01-12 0
2013-01-19 0
2013-01-26 0
Name: Whatev, dtype: int64
非循环版本:
#create DatetimeIndex by last value of index and remove first value by indexing
idx = pd.date_range(s.index[-1], periods=4, freq='7d')[1:]
#append Series to original
s = s.append(pd.Series(np.repeat(0, len(idx)), index=idx))
print(s)
2012-12-29 1
2013-01-05 0
2013-01-12 0
2013-01-19 0
2013-01-26 0
dtype: int64
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句