【问题标题】:Pandas DataFrame lost index after appending rowPandas DataFrame 在追加行后丢失索引
【发布时间】:2022-01-09 08:05:38
【问题描述】:

我创建了一个 DataFrame 并设置了一个索引。如果我通过 append 追加一行,那么索引就会丢失。

import pandas as pd

history = {}
history_cols = {
                "event_time":              "E",
                "close":                   "c",
                "base_volume":             "v",
                "quote_volume":            "q",
                "total_number_of_trades":  "n"
                }

ticks = [
        {'event_time': 1638470651223, 'close': '133.41000000', 'base_volume': '70094.70000000', 'quote_volume': '9415851.87690000', 'total_number_of_trades': 30917},
        {'event_time': 1638470652088, 'close': '133.41000000', 'base_volume': '70094.70000000', 'quote_volume': '9415851.87690000', 'total_number_of_trades': 30917},
        {'event_time': 1638470653224, 'close': '133.41000000', 'base_volume': '70094.70000000', 'quote_volume': '9415851.87690000', 'total_number_of_trades': 30917},
        {'event_time': 1638470654189, 'close': '133.41000000', 'base_volume': '70094.70000000', 'quote_volume': '9415851.87690000', 'total_number_of_trades': 30917},
        {'event_time': 1638470655203, 'close': '133.41000000', 'base_volume': '70094.70000000', 'quote_volume': '9415851.87690000', 'total_number_of_trades': 30917},
        {'event_time': 1638470656201, 'close': '133.41000000', 'base_volume': '70094.70000000', 'quote_volume': '9415851.87690000', 'total_number_of_trades': 30917}
        ]

history["AXSBUSD"] = pd.DataFrame(columns=history_cols.keys())
history["AXSBUSD"].set_index("event_time", inplace=True)
history["AXSBUSD"]

空的DataFrame有索引:

            close   base_volume     quote_volume    total_number_of_trades
event_time              

现在我在一行后面加上一个 dict ...

history["AXSBUSD"] = history["AXSBUSD"].append(ticks[0], ignore_index=True)
history["AXSBUSD"]

...这是结果:

    close   base_volume     quote_volume    total_number_of_trades  event_time
0   133.41000000    70094.70000000  9415851.87690000    30917   1.638471e+12

有人知道为什么索引消失了吗?

【问题讨论】:

  • 你有什么理由一次排地做这件事? history["AXSBUSD"] = history["AXSBUSD"].append(pd.DataFrame(ticks).set_index('event_time')) 使用带有刻度的 DataFrame 构造函数和 set_index,然后附加到字典中的数据帧。
  • 原因是我每秒都会得到一个刻度,我想将它添加到 DataFrame 中,然后进行一些计算,例如移动平均

标签: python pandas dataframe indexing append


【解决方案1】:

与其把它弄得这么复杂,不如干脆:

history["AXSBUSD"] = pd.DataFrame(ticks).set_index('event_time')

如果你需要逐行追加,那么你可以这样做:

history["AXSBUSD"] = pd.DataFrame(columns=history_cols.keys())
history["AXSBUSD"].set_index("event_time", inplace=True)

history["AXSBUSD"] = (history["AXSBUSD"]
                      .append(pd.Series(ticks[0])
                              .rename(ticks[0]['event_time'], inplace=True)
                              .drop('event_time')))
print(history["AXSBUSD"])

输出:

                      close     base_volume      quote_volume   total_number_of_trades  
event_time                                                      
1638470651223  133.41000000  70094.70000000  9415851.87690000  30917

仅将字典附加到数据帧的主要问题是,不清楚新行的索引应该是什么;这就是为什么你必须输入ignore_index=True。但是如果你.rename一个pd.Series被追加,它将作为索引。

但是,我认为最好只追加行而不执行所有这些操作,并且在您真正需要使用数据框时只需 set_index

for tick in ticks:
    history["AXSBUSD"] = history["AXSBUSD"].append(tick, ignore_index=True)
history["AXSBUSD"].set_index('event_time', inplace=True)

【讨论】:

  • 我同意。 +1 不错。
  • 刻度列表仅用于测试。我每秒只会得到一个滴答声,然后想要添加到 DataFrame 中。
  • @noskule 查看我的编辑
【解决方案2】:

不确定这与简单地附加数据框相比效率如何,但这会起作用并满足您的目的:

history["AXSBUSD"] = pd.concat(
    [history["AXSBUSD"], pd.DataFrame([ticks[0]]).set_index("event_time")]
)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2019-02-16
  • 2013-07-18
  • 2015-01-26
  • 2019-04-13
相关资源
最近更新 更多