首页 > 解决方案 > 交换 Pandas DataFrame 的基础数据

问题描述

Pandas 版本 < 1.1.0 允许替换现有 DataFrame 的基础数据。我们使用它从上下文管理器返回一个空的数据帧,并稍后填写数据:

class AnalyzerRecordContext():
    def __init__(self, analyzer):
        self._analyzer = analyzer

    def __enter__(self):
        self.df = pd.DataFrame()
        return self.df  # return empty dataframe

    def __exit__(self, type, value, traceback):
        try:
            df = self._analyzer.stop()  # Returns a complete dataframe
            self.df._data = df._data    # fill returned dataframe
        finally:
            del self._analyzer

# Example Usage
with analyzer.start() as df: # analyzer.start() returns the above Context Manager
  ... Some Code

df.plot()  # DataFrame is now filled with data which was recorded within the context manager
    

从 pandas 版本 1.1.0 开始,这不再可能,因为该行self.df._data = df._data会导致 AttributeError:AttributeError: can't set attribute

更新:搜索 pandas 问题跟踪器,如果发现问题 #33333,其中提到了该_data属性的弃用。该属性已重命名为_mgr,但行为似乎也发生了变化。例如,不再填充索引。所以上面的问题仍然成立。

标签: pythonpandasdataframe

解决方案


所以实际上这要容易得多,而且上面描述的方法过于复杂。无需访问数据框的内部(私有)成员即可完成此操作。以下任何一种方法都有效:

逐列复制:

df1 = ... # Original Dataframe
df2 = pd.DataFrame()  # The empty dataframe
for col in df1.columns:
    df2[col] = df1[col]

一次复制所有列:

df1 = ... # Original Dataframe
df2 = pd.DataFrame()  # The empty dataframe
# Explicit column specification on both dataframes
df2[df1.columns] = df1[df1.columns]
# Column specification only on the new dataframe:
df2[df1.columns] = df1

推荐阅读