如何使用字典和顯式索引值在 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”值,表示“非數字”。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP