我正在练习我的 Python 技能并想要创建系列。 我想使用字典,但是当我想要该系列的索引时,它向我显示 NaN。 我现在不知道是什么原因。 初始字典具有键和值的字符串值,仅包含 8 个元素。
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)
最佳答案
如果从键将字典传递到Series
,则默认创建索引:
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
关于python - 从 dict 创建 python pandas 系列,分配索引的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65193488/