Python Pandas-具有不同列的Concat数据框忽略列名称 [英] Python Pandas - Concat dataframes with different columns ignoring column names

查看:1706
本文介绍了Python Pandas-具有不同列的Concat数据框忽略列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 pandas.DataFrames 想合并为一个.数据框具有相同数量的列,并且顺序相同,但是具有不同语言的列标题.如何有效地组合这些数据框?

I have two pandas.DataFrames which I would like to combine into one. The dataframes have the same number of columns, in the same order, but have column headings in different languages. How can I efficiently combine these dataframes?

df_ger
index  Datum   Zahl1   Zahl2
0      1-1-17  1       2
1      2-1-17  3       4

df_uk
index  Date    No1     No2
0      1-1-17  5       6
1      2-1-17  7       8

desired output
index  Datum   Zahl1   Zahl2
0      1-1-17  1       2
1      2-1-17  3       4
2      1-1-17  5       6
3      2-1-17  7       8

到目前为止,我想到的唯一方法是重命名列标题,然后使用pd.concat([df_ger, df_uk], axis=0, ignore_index=True).但是,我希望找到一种更通用的方法.

The only approach I came up with so far is to rename the column headings and then use pd.concat([df_ger, df_uk], axis=0, ignore_index=True). However, I hope to find a more general approach.

推荐答案

如果列总是相同的顺序,则可以机械地

If the columns are always in the same order, you can mechanically rename the columns and the do an append like:

new_cols = {x: y for x, y in zip(df_uk.columns, df_ger.columns)}
df_out = df_ger.append(df_uk.rename(columns=new_cols))

测试代码:

df_ger = pd.read_fwf(StringIO(
    u"""
        index  Datum   Zahl1   Zahl2
        0      1-1-17  1       2
        1      2-1-17  3       4"""),
    header=1).set_index('index')

df_uk = pd.read_fwf(StringIO(
    u"""
        index  Date    No1     No2
        0      1-1-17  5       6
        1      2-1-17  7       8"""),
    header=1).set_index('index')

print(df_uk)
print(df_ger)

new_cols = {x: y for x, y in zip(df_uk.columns, df_ger.columns)}
df_out = df_ger.append(df_uk.rename(columns=new_cols))

print(df_out)

结果:

         Date  No1  No2
index                  
0      1-1-17    5    6
1      2-1-17    7    8

        Datum  Zahl1  Zahl2
index                      
0      1-1-17      1      2
1      2-1-17      3      4

        Datum  Zahl1  Zahl2
index                      
0      1-1-17      1      2
1      2-1-17      3      4
0      1-1-17      5      6
1      2-1-17      7      8

这篇关于Python Pandas-具有不同列的Concat数据框忽略列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆