问题
I am practicing my Python skills and want to create series. I want to use dictionary, but when I want to have index for the series, it shown to me NaN. I do not now what is the reason. The initial dictionary has string values for the keys and the values, contains only 8 elements.
country_capital_dict = {'Germany':'Berlin', 'US':'Washington',
'Italy':'Rome', 'France':'Paris',
'Russia':'Moscow','Spain':'Madrid',
'Austria':'Vienna','Greece':'Athens'}
country_capital_series = pd.Series(country_capital_dict, index = ['a','b','c','d','e','f','g','h'])
print(country_capital_series)
回答1:
If pass dictionary to Series
from keys is created index by default:
country_capital_dict = {'Germany':'Berlin', 'US':'Washington',
'Italy':'Rome', 'France':'Paris',
'Russia':'Moscow','Spain':'Madrid',
'Austria':'Vienna','Greece':'Athens'}
country_capital_series = pd.Series(country_capital_dict)
print(country_capital_series)
Germany Berlin
US Washington
Italy Rome
France Paris
Russia Moscow
Spain Madrid
Austria Vienna
Greece Athens
dtype: object
If need change index you can assign it:
country_capital_series.index = ['a','b','c','d','e','f','g','h']
print(country_capital_series)
a Berlin
b Washington
c Rome
d Paris
e Moscow
f Madrid
g Vienna
h Athens
dtype: object
Or pass only values of dictionary to Series
:
country_capital_series = pd.Series(country_capital_dict.values(),
index = ['a','b','c','d','e','f','g','h'])
print(country_capital_series)
a Berlin
b Washington
c Rome
d Paris
e Moscow
f Madrid
g Vienna
h Athens
dtype: object
Reason why get all missing values is mismatch between index from list and index from keys of dictionary - because different pandas try change original index by new from list and dont know new values, so assigned all NaNs:
country_capital_series = pd.Series(country_capital_dict,
index = ['a','b','c','d','e','f','g','h'])
print(country_capital_series)
a NaN
b NaN
c NaN
d NaN
e NaN
f NaN
g NaN
h NaN
dtype: object
If only some values matching are assigned NaNs only for not match values:
country_capital_series = pd.Series(country_capital_dict,
index = ['a','Germany','c','d','e','Austria','g','h'])
print(country_capital_series)
a NaN
Germany Berlin
c NaN
d NaN
e NaN
Austria Vienna
g NaN
h NaN
dtype: object
来源:https://stackoverflow.com/questions/65193488/create-python-pandas-series-from-dict-problem-to-assign-index