Home > Software engineering >  Add column names in each cell of a pandas data frame
Add column names in each cell of a pandas data frame

Time:05-05

I have a dataframe like below enter image description here

I need to add the column name as key value pair inside each cell eg: {"colname": "Ship Mode label"}

How to do that in pandas?

CodePudding user response:

A simple loop should work to update the dictionaries in place:

for col in df:
    for s in df[col]:
        s['colname'] = col

example input:

df = pd.DataFrame({'A': [{'a': 1, 'b': 2}], 'B': [{'a': 1, 'b': 2}]})

output:

                                  A                                 B
0  {'a': 1, 'b': 2, 'colname': 'A'}  {'a': 1, 'b': 2, 'colname': 'B'}

CodePudding user response:

Hope I understand correctly:

reproducible start (this should give you a data frame similar to the one in the image above):

DF = pd.DataFrame([[{'value': 'Second Class label', 'frequency': 10309}, {'value': 'India label', 'frequency': 10309}],
         [{'value': 'First Class label', 'frequency': 7505}, {'value': 'USA label', 'frequency': 7000}]],
        columns= ['Ship Mode Label', 'Country Label'])

you can add elements to the dict for example by a simple loop like this.

for column in DF.columns:
    for row in DF.index:
        DF.loc[row, column]["colname"] = column

This should add to each dictionary in the cell the information as required like so:

DF.loc[1, "Ship Mode Label"]

{'value': 'First Class label', 'frequency': 7505, 'colname': 'Ship Mode Label'}

hope it helps

  • Related