Append dataframes with different column names - Pandas

后端 未结 3 2066
借酒劲吻你
借酒劲吻你 2020-12-21 16:17

I have 3 dataframes which can be generated from the code shown below

df1= pd.DataFrame({\'person_id\':[1,2,3],\'gender\': [\'Male\',\'Female\',\'Not disclose         


        
3条回答
  •  天涯浪人
    2020-12-21 16:43

    As per pandas documentation, you can do this creating a mapping:

    df2.rename(columns={column1:'ethn', column2:'gen', column3:'pers_id'}, inplace=True)
    

    Now, you clearly stated that you have to do this runtime. If you know that number of columns and their respective positions won't change, you can collect the actual column names with df2.columns(), that should output something like that:

    ['ethnicity', 'gender', 'person_id']
    

    At this point, you can create the mapping as:

    final_columns = ['ethn', 'gen', 'pers_id']
    previous_columns = df2.columns()
    mapping = {previous_columns[i]: final_columns[i] for i in range(3)}  # 3 is arbitrary.
    

    And then just call

    df2.rename(mapping, inplace=True)
    

提交回复
热议问题