gpt4 book ai didi

python - 向 Pandas DataFrame 添加一行会重复索引

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:59 25 4
gpt4 key购买 nike

我有一个带有日期时间对象类型索引的 DataFrame。我最终将使用 HDFStore.append 将此 DataFrame 写入 HDF5 文件。我添加了很多需要写入此 HDF5 文件的行。如果我对每一行使用 HDFStore.append,这会花费太长时间。如果我首先将所有内容收集到 DataFrame 中,则会耗尽内存。所以我需要间歇性地分块并写入 HDF5。

df = DataFrame([['Bob','Mary']], columns=['Boy', 'Girl'], index=[datetime.today()])

现在我想用相同的索引添加另一行

row = ['John', 'Sue']

使用 .loc 或 .ix 替换现有行

df.loc[datetime.today()] = row

使用追加可以工作,但对于我的目的来说太慢了

new_df = DataFrame([row], columns=df.columns, index=[datetime.today()])
df.append(new_df)

有更好的方法吗?

最佳答案

创建列表列表并制作其数据框将比追加更快。既然您已经在创建小块的数据帧,为什么不一次性创建它:

In [1303]: pd.DataFrame([[0,1], [1,2], [2,3]], index=[pd.datetime.today()] * 3)
Out[1303]:
0 1
2015-05-07 09:02:30.327473 0 1
2015-05-07 09:02:30.327473 1 2
2015-05-07 09:02:30.327473 2 3

关于python - 向 Pandas DataFrame 添加一行会重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30088843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com