简体   繁体   中英

Create a dictionary from pandas empty dataframe with only column names

I have a pandas data frame with only two column names( single row, which can be also considered as headers).I want to make a dictionary out of this with the first column being the value and the second column being the key.I already tried the to.dict() method, but it's not working as it's an empty dataframe.

Example df=|Land |Norway| to {'Land': Norway}

I can change the pandas data frame to some other type and find my way around it, but this question is mostly to learn the best/different/efficient approach for this problem.

For now I have this as the solution:

dict(zip(a.iloc[0:0,0:1],a.iloc[0:0,1:2]))

Is there any other way to do this?

Very manual solution

df = pd.DataFrame(columns=['Land', 'Norway'])

df = pd.DataFrame({df.columns[0]: df.columns[1]}, index=[0])

If you have any number of columns and you want each sequential pair to have this transformation, try:

df = pd.DataFrame(dict(zip(df.columns[::2], df.columns[1::2])), index=[0])

Note: You will get an error if your DataFrame does not have at least two columns.

Here's a simple way convert the columns to a list and a list to a dictionary

def list_to_dict(a):
    it = iter(a)
    ret_dict = dict(zip(it, it))
    return ret_dict

df = pd.DataFrame([], columns=['Land', 'Normway'])
dict_val = list_to_dict(df.columns.to_list())
dict_val # {'Land': 'Normway'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM