python - 交换 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
- 是否有其他方法可以使用公共熊猫 API 获得相同的结果?
- 这个问题一般有更好的解决方案吗?
更新:搜索 pandas 问题跟踪器,如果发现问题 #33333,其中提到了该_data
属性的弃用。该属性已重命名为_mgr
,但行为似乎也发生了变化。例如,不再填充索引。所以上面的问题仍然成立。
解决方案
所以实际上这要容易得多,而且上面描述的方法过于复杂。无需访问数据框的内部(私有)成员即可完成此操作。以下任何一种方法都有效:
逐列复制:
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
推荐阅读
- c - 在文件中搜索单词并以字节为单位打印它们的位置?
- java - 带有存储库的 Elasticsearch 配置最终在 Spring Boot 上出现异常
- css - 如何为移动视图自定义 ngx-bootstrap datepicker 的位置?
- r - 在 R 中带来长到宽的数据而不会丢失值
- r - 用 lavaan 估计观测变量的协方差
- python - Numpy - 使用满足条件的数组值
- django - Django Apache2 VirtualEnv - 服务器没有响应
- vue.js - 未在 SFC 中定义的组件不使用 Vue3 Router 显示?
- python - 将数据框绘制为条形图,每列在单独的 y 轴上
- php - PHP - Symfony 的 CSRF 保护