Python 如何创建固定长度的数据帧

Python 如何创建固定长度的数据帧,python,dataframe,Python,Dataframe,创建数据框以更新最近三天的价格 #Initial value with prices price_3days=pd.DataFrame({'Day_of_month': [1,2,3], 'Price': [1000, 1100, 1200]}) #Price to be updated Day_of_month_today=4 Price_today=1300 if (Day_of_month_today > price_3days['Day_of_month'].iloc[-1])

创建数据框以更新最近三天的价格

#Initial value with prices
price_3days=pd.DataFrame({'Day_of_month': [1,2,3], 'Price': [1000, 1100, 1200]})

#Price to be updated
Day_of_month_today=4
Price_today=1300

if (Day_of_month_today > price_3days['Day_of_month'].iloc[-1]):
    new_row=pd.DataFrame({'Day_of_month': [Day_of_month_today], 'Price': [Price_today]})
price_3days.drop(price_3days.head(1).index, inplace=True)
price_3days.reset_index(drop=True, inplace=True)
price_3days=price_3days.append(new_row)
price_3days.reset_index(drop=True, inplace=True)  
print(price_3days)

#Result

Day_of_month  Price
0             2   1100
1             3   1200
2             4   1300
当我输入月份的第二天和价格时,列表未更新,仅更新最后一天。 如何使用“最近三天”条目更新列表。
我是编程新手。

如果我没有完全误解您的问题,那么您的代码做的是正确的。您将删除第一行(最早的),并追加新行。尽管如此,使用
.append
更新pd.DataFrame并不是非常有效,尤其是如果您多次这样做,因为pandas必须一次又一次地复制所有数据

这是您的代码,经过一些优化。您可以编辑第一个
.reset\u index
。您可以使用所谓的链式分配,在这里,您可以使用
连接数据帧的所有更改(我用
()
将所有语句括起来,这样就可以将它们拆分为多行)


但也许口述对你更有帮助。如果您添加更多信息,即您希望实现的目标,我可以为您提供更多建议,说明如何实施不同的解决方案。

我将每天输入“今日月日”和“今日价格”的值。我的数据框应该显示最近三天的条目。使用此代码,只有第三行得到更新。每当创建新条目时,我希望第三行代替第二行,第二行代替第一行。当我执行您的代码或我的版本时,所有三行都会更新。代码示例中发布的结果也显示了更新的数据帧。我错过了一些基本的东西吗?我的意思是,第一排被取消了。因此,前第二排现在是第一排,前第三排现在是第二排。然后,追加新行,并将索引重置为(0,1,2)。
#Initial value with prices
price_3days=pd.DataFrame({'Day_of_month': [1,2,3], 'Price': [1000, 1100, 1200]})

#Price to be updated
Day_of_month_today=4
Price_today=1300

if (Day_of_month_today > price_3days['Day_of_month'].iloc[-1]):
    new_row=pd.DataFrame({'Day_of_month': [Day_of_month_today], 'Price':[Price_today]})
    price_3days = (price_3days.drop(price_3days.head(1).index)
                  .append(new_row)
                  .reset_index(drop=True))