Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạo cấu trúc Series trong Python từ giá trị scalar/hằng số

Giá trị scalar/hằng số định nghĩa một lần, lặp lại trên tất cả hàng/entry của cấu trúc Series. Ví dụ:

Ví dụ 1: Với index tùy chỉnh

import pandas as pd

my_index = ['ab', 'mn', 'gh', 'kl']
my_series = pd.Series(7, index=my_index)
print("Series tạo từ giá trị scalar và chỉ định index:")
print(my_series)

Đầu ra

Series tạo từ giá trị scalar và chỉ định index:
ab    7
mn    7
gh    7
kl    7
dtype: int64

Giải thích

  • Nhập thư viện cần thiết, đặt bí danh để dễ dùng.
  • Tạo danh sách giá trị index.
  • Truyền giá trị hằng số cho hàm Series trong pandas.
  • Cùng truyền index list.
  • Hiển thị trên console.

Nếu index không tùy chỉnh, giá trị mặc định từ 0. Vì chỉ có 1 giá trị hằng số, chỉ có 1 entry trong Series. Minh họa:

Ví dụ 2: Index mặc định

import pandas as pd

my_series = pd.Series(7)
print("Series tạo từ giá trị scalar và index mặc định:")
print(my_series)

Đầu ra

Series tạo từ giá trị scalar và index mặc định:
0    7
dtype: int64

Giải thích

  • Nhập thư viện cần thiết, đặt bí danh để dễ dùng.
  • Truyền giá trị hằng số cho hàm Series trong pandas.
  • Hiển thị trên console.

Ứng dụng thực tế: Tạo Series hằng số để broadcast trong phép toán: df['col'] + pd.Series(5, index=df.index). Hoặc tạo cột constant trong DataFrame: df['const'] = 1 (Pandas tự broadcast).