python - 如何将 for 循环中的 .pkl 文件附加到 for 循环中创建的 pandas 数据帧?
问题描述
我有一段看似简单的代码,但不知何故它不起作用。代码的目标是在文件夹中查找所有泡菜数据,将 for 循环中的第一个作为 pandas 数据框加载,该数据框在以前不存在的变量下命名,如果变量存在,则应加载剩余的泡菜文件作为 pandas 并将它们附加到第一个循环中新创建的 pandas 数据框:
import pandas as pd
import os
# Creating the first Dataframe using dictionary
df1 = pd.DataFrame({"a":[1, 2, 3, 4],
"b":[5, 6, 7, 8]})
# Creating the Second Dataframe using dictionary
df2 = pd.DataFrame({"a":[1, 2, 3],
"b":[5, 6, 7]})
df1.append(df2)
印刷精美:
a b
0 1 5
1 2 6
2 3 7
3 4 8
0 1 5
1 2 6
2 3 7
但是,当我尝试将存储的 pickle 文件中的数据帧附加到 for 循环中时,它不会打印错误,但它仅适用于第一个数据帧:
df1.to_pickle("DF1.pkl")
df2.to_pickle("DF2.pkl")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
#The line above should produce the line below
files=["DF1.pkl", "DF2.pkl"]
for i in files:
if ".pkl" in i:
if "ALL_DATA" not in globals():
ALL_DATA=pd.read_pickle(i)
else:
ALL_DATA.append(pd.read_pickle(i))
仅打印:
a b
0 1 5
1 2 6
2 3 7
3 4 8
谁能帮我澄清一下?
解决方案
DataFrame.append
返回一个新对象,因此尽管您调用ALL_DATA.append(pd.read_pickle(i))
时从未将其写回 ALL_DATA ,但这些更改将被丢弃。您需要重新分配更改:
ALL_DATA = ALL_DATA.append(pd.read_pickle(i))
但是,在循环中追加是低效的,因为它会在每次迭代时复制数据,所以你应该避免它。相反,追加到一个列表,这很快,然后concat
在循环之后一次。
l = [] # Holds everything you may possibly append
for i in files:
if ".pkl" in i:
if "ALL_DATA" not in globals():
ALL_DATA=pd.read_pickle(i)
else:
l.append(pd.read_pickle(i)) # List append which modifies `l`
# Create df from ALL_DATA and everything that you append
ALL_DATA = pd.concat([ALL_DATA, *l])
推荐阅读
- javascript - document.querySelector 跳过不存在的元素
- django - 获取“未提供身份验证凭据。” 尝试访问我的 ModelViewSet URL 时的消息
- flutter - 返回页面时如何处理graphql查询的重建(Flutter)?
- python - 基于groupby拆分csv文件千次
- firebase - 对 Firebase MLNLTranslate 的 Catalyst 支持
- javascript - D3.js 条形图比例/范围问题。条形图太低
- express - 有没有办法实现谷歌身份验证颤振?
- css - 顺风 css 响应式弯曲方向的问题
- javascript - 从 created() VueJS 上的另一个组件获取数据
- mysql - 为什么我的 java 查询会导致错误但在 Workbench 中很好?