简体   繁体   中英

How to create a pandas Series from dict with non unique keys?

I am trying to create a pandas Series from dict that contains non-unique keys. But pandas keep discarding similar keys and loads only the last one.

    my_dict1= {'Country':'US','Country':'UK','Country':'Japan','Country':'China',}
    pd.Series(my_dict1)

Output:

Country    China
dtype: object

Any turn arround possible that it inclues all the keys and values

Dict needs unique keys. You need to do something as below, second option can be created by dict + zipping the list of countries with a range.

Option 1

my_dict1= {'Country1':'US','Country2':'UK','Country3':'Japan','Country4':'China',}

Option 2

country_list = ["US","UK"]
indexes = range(2)
country_dict = dict(zip(indexes,country_list))

Output

country_dict={'0':'US', '1':'UK',}

您可能将其更改为:


pd.Series([v for k, v in mydict.items()])

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