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

标签 python pandas series

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

相关文章:

python - 如果我只是从 numpy 模块引用它,为什么我必须从 numpy 导入它

python - 使用 Pandas DataFrames 比较两个标题不同但行数据相同的 excel 文件

python - 验证图像处理中的去噪功能的最佳测量是什么?信噪比似乎让我失望

Python 忽略非空值之后的 DataFrame 行

python - 统计pandas中不同时间范围内的记录数

python - 在 python 中转换框架 pandas

python - Pandas :根据特定列的值计数选择行

javascript - Highcharts.js 不会呈现图表,它表示错误 "Cannot read property ' 系列' of undefined”

python - 不使用索引python访问系列对象的元素,访问相关值或其他矩阵

python-3.x - Python/Pandas 2 系列的元素明智联合,每个元素中包含集合