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
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)