python - 合并几个不同大小的熊猫数据框
问题描述
我的数据框如下所示:
007538839
0 105586.180
1 105582.910
2 105585.230
3 105576.445
4 105580.016
df1.shape = (69302, 1)
这只有一列名称为“007538839”。我还有其他几个数据框也有这样的一列,但列名和行大小不同。
007543167
0 39886.620
1 39908.777
2 39886.574
3 39884.340
4 39871.098
df2.shape = (69778, 1)
我想在一个看起来像这样的循环中将所有这些合并在一起:
import os
base_dir = ''
for root, dirs, files in os.walk(base_dir, topdown=False):
for name in files:
if root.count(os.sep) == 3 and name.endswith(".csv"):
file_path = os.path.join(root, name)
#merge all files
我的目标是不删除任何行,对于还没有值的行,将分配 NaN。例如,如果我合并 df1 和 df2 我应该得到 69778 行的东西。
解决方案
首先通过 append 创建字典列表,然后使用concat
with axis=1
:
import os
dfs = []
base_dir = ''
for root, dirs, files in os.walk(base_dir, topdown=False):
for name in files:
if root.count(os.sep) == 3 and name.endswith(".csv"):
file_path = os.path.join(root, name)
df = pd.read_csv(file_path)
dfs.append(df)
df = pd.concat(dfs, axis=1)
推荐阅读
- flutter - 如何设置 CupertinoDatePicker 的位置?
- python - Django-Haystack 无法获取模板 .txt 文件中的数据
- python - 如何将接口中的值存储到不同的文件中
- jquery - 禁用 about:blank 用于 Datatable 打印
- xamarin - 集合视图中的复选框试图获取值
- r - R错误消息:固定术语是“cond((Int))”和“disp((Int))”
- react-konva - 调整组内文本的大小
- html - 烧瓶插座 | 使用 Flask Executor 或 ThreadPoolExecutor 创建的后台任务更新和绘制图表
- c++ - 使用指针参数绑定函数中的错误
- regex - 如何组合 REGEXP_CONTAINS