如何使用字典和显式索引值在 Python 中创建序列数据结构?


让我们了解如何使用字典创建序列数据结构,以及如何为序列指定索引值,即自定义索引值。

字典是一种 Python 数据结构,它具有映射结构 - 键值对。

示例

 实时演示

import pandas as pd
my_data = {'ab' : 11., 'mn' : 15., 'gh' : 28., 'kl' : 45.}
my_index = ['ab', 'mn' ,'gh','kl']
my_series = pd.Series(my_data, index = my_index)
print("This is series data structure created using dictionary and specifying index values")
print(my_series)

输出

This is series data structure created using dictionary and specifying index values
ab  11.0
mn  15.0
gh  28.0
kl  45.0
dtype: float64

解释

  • 导入所需的库,并为易用性提供别名。
  • 创建一个字典数据结构,并在其中定义键值对。
  • 接下来,将自定义索引值存储在列表中。
  • 这些值与字典中“键”的值相同。
  • 然后在控制台上打印它。

如果索引中的值大于字典中的值会发生什么?

让我们看看当索引中的值大于字典中的值时会发生什么。

示例

 实时演示

import pandas as pd
my_data = {'ab' : 11., 'mn' : 15., 'gh' : 28., 'kl' : 45.}
my_index = ['ab', 'mn' ,'gh','kl', 'wq', 'az']
my_series = pd.Series(my_data, index = my_index)
print("This is series data structure created using dictionary and specifying index values")
print(my_series)

输出

This is series data structure created using dictionary and specifying index values
ab  11.0
mn  15.0
gh  28.0
kl  45.0
wq  NaN
az  NaN
dtype: float64

解释

  • 导入所需的库,并为易用性提供别名。

  • 创建一个字典数据结构,并在其中定义键值对。

  • 接下来,将与字典中元素相比数量更多的自定义索引值存储在列表中。

  • 然后在控制台上打印它。

可以看出,索引值中剩余的值被赋予“NaN”值,表示“非数字”。

更新于: 2020年12月10日

132 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.