我正在尝试使用iloc替换熊猫数据框的最后一行,但是我无法使其正常工作。那里有很多解决方案,但是最简单(最慢)在这里:
How to do a FIFO push-operation for rows on Pandas dataframe in Python?
为什么此方法在下面的代码中不起作用?
def append_from_dataframe(self,timeframe,new_dataframe):
new_dataframe.reset_index(inplace=True)
temp_dataframe = self.timeframedict.get(timeframe)
num_rows_existing = temp_dataframe.shape[0]
num_rows_new = new_dataframe.shape[0]
overlap = (num_rows_existing + num_rows_new) - 500
# slow, replace with numpy array eventually
if overlap >= 1:
# number of rows to shift
i = overlap * -1
#shift the dataframe back in time
temp_dataframe = temp_dataframe.shift(i)
#self.timeframedict.get(timeframe) = self.timeframedict.get(timeframe).shift(overlap)
#replace the last i rows with the new values
temp_dataframe.iloc[i:] = new_dataframe
self.timeframedict.update({timeframe:temp_dataframe})
else:
#TODO - see this https://stackoverflow.com/questions/10715965/add-one-row-in-a-pandas-dataframe
self.timeframedict.update({timeframe:self.timeframedict.get(timeframe).append(new_dataframe)})
要替换另一行的数据框内容:
ipdb> new_dataframe
Timestamp Open High Low Close Volume localtime
0 1533174420000 423.43 423.44 423.43 423.44 0.73765 1533174423776
temp_dataframe.shift(i)
将值移回一,将值替换为NaN-
ipdb> temp_dataframe.iloc[i:]
Timestamp Open High Low Close Volume localtime
499 NaN NaN NaN NaN NaN NaN NaN
但是temp_dataframe.iloc[i:] = new_dataframe
不能替代任何内容。
编辑:我应该补充一点,在玩了一段时间之后,我可以将1行替换为:
temp_dataframe.iloc[-1] = new_dataframe.iloc[0]
但是,我无法使用多行版本
答案 0 :(得分:1)
df = pd.DataFrame({'a':[1,2,3,4,5],'b':['foo','bar','foobar','foobaz','food']})
输出:
df
Out[117]:
a b
0 1 foo
1 2 bar
2 3 foobar
3 4 foobaz
4 5 food
分别用第二行和第一行替换最后两行(foobaz和food):
df.iloc[-2:]=[df.iloc[1],df.iloc[0]]
df
Out[119]:
a b
0 1 foo
1 2 bar
2 3 foobar
3 2 bar
4 1 foo
您也可以这样做以获得相同的结果:
df.iloc[-2:]=df.iloc[1::-1].values