Home > Mobile >  Modify dataframe columns dynamically based on user input
Modify dataframe columns dynamically based on user input

Time:04-21

I have the following dataframe with certain numbers of columns.

id  column1 column2 column3 column4
0   X       A       P       S
1   Y
2   Z

user has to give the input via the .txt file which contains the parameters for the new columns which has to be added to the current dataframe. the .txt file has the following content.

{
    "new_case": {        
        "N": 2,        
        "concept:name": [
            "column1",
            "column3",
            "column4"
        ]
    }
}

The new column in the dataframe should contain the values from a mentioned column in the.txt file.

Expected output.

id  column1 column2 column3 column4 new_column
0   X       A       P       S       X P S
1   Y                               Y Nan Nan
2   Z                               Z Nan Nan

Any help is appreciated :) Thank you.

CodePudding user response:

Just an example on your example data

import json
import pandas as pd


with open('input.txt', 'r', encoding='utf-8') as f:
    data = json.loads(f.read())

df['new_column'] = df[data['new_case']['concept:name']].fillna('Nan').agg(' '.join, axis=1)
print(df)

   id column1 column2 column3 column4 new_column
0   0       X       A       P       S      X P S
1   1       Y    <NA>    <NA>    <NA>  Y Nan Nan
2   2       Z    <NA>    <NA>    <NA>  Z Nan Nan
  • Related