Home > database >  Create dictionary {(row, column): cell value} from dataframe
Create dictionary {(row, column): cell value} from dataframe

Time:10-27

From a given dataframe, I am trying to create a dictionary with the following format: {(row, column):'cell value'}. I am aware of pandas.DataFrame.to_dict, but that creates a dictionary of dictionaries: {row:{column:'cell value'}}.

Would you have any code suggestions? Would loop be a good idea?

CodePudding user response:

You could loop over the rows and columns and use .loc to get the corresponding value.

{(row, col): df.loc[row, col] for row in df.index for col in df.columns}

For demonstration, if df is:

            max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8

The result is:

{('cobra', 'max_speed'): 1,
 ('cobra', 'shield'): 2,
 ('viper', 'max_speed'): 4,
 ('viper', 'shield'): 5,
 ('sidewinder', 'max_speed'): 7,
 ('sidewinder', 'shield'): 8}

[This df is from the Pandas documentation.]

CodePudding user response:

Take the result of to_dict and create a new dict:

result = {}
for column, inner_dict in df.to_dict().items():
    for row, value in inner_dict.items():
        result[(row, column)] = value

CodePudding user response:

You can use this code it's makeing your data fram to list of dictionary's

Panda.DataFrame.to_dict(orient="records")

Then using a for loop

  • Related