我有两个数据框,我正在尝试合并它们。
带有标题的 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/