Home > Net >  Convert first row of excel into dictionary
Convert first row of excel into dictionary

Time:10-04

I am trying to convert first header row of excel table into dict with a value of 1. Fairly new to Python and not able to excute this code. My table in spreadhseet looks like:

Matrix Column A Column B
Row A 10 20
Row B 30 40

I would like my output as following dict: {'Column A': 1,'Column B': 1}

I tried test_row = pd.read_excel("Test.xlsx", index_col=0).to_dict('index')

The column names will increase in future. So, it will be nice to have a solution that can extract n number of columns header into dict with a value of 1. Many thanks!

CodePudding user response:

Given your example Dataframe as

df = pd.DataFrame({'Matrix': {0: 'Row A', 1: 'Row B'}, 'Column A': {0: 10, 1: 30}, 'Column B': {0: 20, 1: 40}})

You can use:

cols_dict = {col: 1 for col in df.columns}  # {'Matrix': 1, 'Column A': 1, 'Column B': 1}
rows_dict = {row: 1 for row in df.Matrix}  # {'Row A': 1, 'Row B': 1}
  • Related