简体   繁体   中英

Key is shown as nan in dictionary python

I am trying to convert a dataframe with 2 columns as dictionary with first column being key and second its value all in one dictionary.

Data sample:

id           summary
135791059    blha blah blah
135791051    blah something blah

And here is the code I have tried

map_of_values = pd.Series(f_dataframe.summary.values,index=f_dataframe.id).to_dict()

print(map_of_values)

The output is:

{'id': {'blah blah blah': nan, 'blah something blah}

I want it to be :

 {135791059:'blah blah blah blah',135791051:'blah something blah'}

What wrong am I doing? And also I want to iterate over each key value pair builing a string from it. Is it the right way?

您可以简单地使用以下代码:

df.set_index('id').to_dict()['summary']

Tried your solution as below.

working fine. Unable to reproduce the error. Maybe you want to check into your created data-frame.

f_dataframe= {'id':[135791059,135791051],
        'summary':["blha blah blah", "blah something blah"]}
df = pd.DataFrame(f_dataframe)

map_of_values = df.set_index('id').to_dict()['summary']
print(map_of_values)
  • df.to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter.
  • orient - String value, ('dict', 'list', 'series', 'split', 'records', 'index') Defines which dtype to convert Columns(series into).

Ex.

import pandas as pd

my_dict = {'id':[135791059,135791051],'summary':["blha blah blah", "blah something blah"]}
df = pd.DataFrame(my_dict)
print(df)
records = df.to_dict('records')
data = {i['id'] :i['summary'] for i in records}
print(data)

O/P:

          id              summary
0  135791059       blha blah blah
1  135791051  blah something blah

{135791059: 'blha blah blah', 135791051: 'blah something blah'}

This problem mostly happens if you already have used the values as a column. IF you have an existing column and want to attribute some 'key's to the values and make a new column, it will appear as NaN . You need to use the existing column as the 'key' and the desired new column as 'values' (by just switching the position of key and value in your dictionary).

For example: your pre-existing column is summary and your current dict is:

d = {135791059: 'blah blah blah', 135791051: 'blah something blah'}

However, You need to correct it like:

d = {'blah blah blah': 135791059: , 'blah something blah': 135791051}

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