You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环按列拼接DataFrame后结果为空,该如何修复?

修复Pandas横向拼接后结果为空的问题

问题场景

你通过循环读取CSV文件生成DataFrame,尝试将它们横向拼接至初始为空的result中,但最终输出的result却为空。原代码如下:

result = pd.DataFrame()
for bench in benchmarks:
    df = read_raw(bench)
    print(df)
    result = pd.concat([result, df], axis=1, join="inner")
print(result.info())

运行输出显示单个df存在有效数据,但result为空:

$ python3 test.py
                  launch
0                      1
1                    524
2                   3611
3                   3611
4                    169
...                  ...
92515                143
92516                138
92517                169
92518                138
92519               1048

[92520 rows x 1 columns]
<class 'pandas.core.frame.DataFrame'>
Index: 0 entries
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   M1      0 non-null      int64

问题原因

初始的result是空DataFrame,第一次执行pd.concat时,join="inner"要求两个DataFrame有共同索引,但空DataFrame没有任何索引项,导致第一次拼接直接得到空结果。后续循环中,空的result和新的df做内连接,结果依然为空。

修复方案

方案1:跳过初始空DataFrame的第一次拼接

将result初始化为None,第一次循环直接赋值,后续再执行拼接操作:

result = None
for bench in benchmarks:
    df = read_raw(bench)
    print(df)
    if result is None:
        result = df
    else:
        result = pd.concat([result, df], axis=1, join="inner")
print(result.info())

方案2:先收集所有DataFrame,最后一次性拼接

这种方式更高效,也彻底避免了初始空df的问题:

dfs = []
for bench in benchmarks:
    df = read_raw(bench)
    print(df)
    dfs.append(df)
result = pd.concat(dfs, axis=1, join="inner")
print(result.info())

额外提示

如果各个df的索引不一致,但你需要保留所有行,可以将join="inner"改为join="outer",不过这会引入缺失值,需根据业务需求选择。

内容的提问来源于stack exchange,提问作者mahmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:10:37