如果将字典传递给Series
from key 默认创建索引:
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
如果需要更改索引,您可以分配它:
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
或者仅将字典的值传递给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
获取所有缺失值的原因是列表中的索引与字典键中的索引之间不匹配 - 因为不同的 pandas 尝试通过列表中的新值更改原始索引并且不知道新值,因此分配了所有 NaN:
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
如果仅对某些匹配的值分配 NaN,则仅针对不匹配的值:
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