python - pandas.concat 两个数据框(一个有标题,一个没有标题)

标签 python python-3.x pandas xlrd

我有两个数据框,我正在尝试合并它们。

带有标题的 json 文件:

| category 1 | category 2  | category 3   | category 4   |
|:-----------|------------:|:------------:|:------------:|
|   name1    | attribute1  |   amount1    | other1       |
|   name2    | attribute2  |   amount2    | other2       |

还有一个包含相同格式数据但没有标题的 Excel 文件:

|:-----------|------------:|:------------:|:------------:|
|   name3    | attribute3  |   amount3    | other3       |
|   name4    | attribute4  |   amount4    | other4       |

我正在尝试实现以下数据框:

| category 1 | category 2  | category 3   | category 4   |
|:-----------|------------:|:------------:|:------------:|
|   name1    | attribute1  |   amount1    | other1       |
|   name2    | attribute2  |   amount2    | other2       |
|   name3    | attribute3  |   amount3    | other3       |
|   name4    | attribute4  |   amount4    | other4       |

我的代码:

import pandas as pd
import json
import xlrd

data = pd.read_json('pandas_test.json', orient='split')
data2 = pd.read_excel("guys2.xlsx", header=None)
data = pd.concat([data, data2])

问题: 当我运行我的代码时,组合数据框如下所示:

| category 1 | category 2  | category 3   | category 4   |     1     |     2      |     3     |     4     |
|:-----------|------------:|:------------:|:------------:|:---------:|:----------:|:---------:|:---------:|
|   name1    | attribute1  |   amount1    | other1       |   NaN     |    NaN     |   NaN     |   NaN     |
|   name2    | attribute2  |   amount2    | other2       |   NaN     |    NaN     |   NaN     |   NaN     |
|    NaN     |     NaN     |     NaN      |    NaN       |  name3    | attribute3 |   amount3 |   other3  |
|    NaN     |     NaN     |     NaN      |    NaN       |  name4    | attribute4 |   amount4 |   other4  |

我已经尝试使用一些属性的 concat 函数,例如 ignore_index=True,但到目前为止没有任何效果。

最佳答案

试试

data2.columns=data.columns
data = pd.concat([data, data2])

关于python - pandas.concat 两个数据框(一个有标题,一个没有标题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927219/

相关文章:

python - LIME 功能解释产生无效 key 错误

python - 如何在不安装的情况下使用打包的Python包

python - 摆脱 'Can' t 绘制到关闭窗口的错误

python - python 3 中最快的标准输入/输出 IO?

python - 单个应用程序的 Django URL 路由

python - 在 Python 中交互运行外部可执行文件

python - 按 T​​rue 序列分组

python - Bokeh 中的 TimeSeries 使用带索引的数据框

python - 将变化率列添加到 Pandas DataFrame

python-3.x - 如何在 pandas 数据框中用 regex 分隔一个字符串和一个空格?