从 dict 创建 python pandas 系列,分配索引的问题

2024-01-10

我正在练习我的 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)

如果将字典传递给Seriesfrom 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 dict 创建 python pandas 系列,分配索引的问题 的相关文章

随机推荐