创建 Series
从 Python 列表、字典和 NumPy 数组构建 Pandas Series,并查看其 index 和 values 属性。
创建 Series 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What Is a Pandas Series?
A Pandas Series is a one-dimensional labelled array capable of holding any data type — integers, floats, strings, Python objects, or even other Series. Think of it as a NumPy array with a custom index (labels for each element). The index is what makes Series much more powerful than plain arrays for data analysis tasks where values need descriptive names.
import pandas as pd
import numpy as np
s = pd.Series([10, 20, 30, 40])
print(s)
# 0 10
# 1 20
# 2 30
# 3 40
# dtype: int64Creating a Series from a Python List
Passing a Python list to pd.Series() creates a Series with a default integer RangeIndex (0, 1, 2, ...). You can provide custom index labels via the index= parameter. The length of the index list must match the length of the data. Labels can be strings, integers, dates, or any hashable Python objects.
import pandas as pd
temps = pd.Series([22.5, 19.0, 25.3, 17.8],
index=['Mon', 'Tue', 'Wed', 'Thu'])
print(temps)
# Mon 22.5
# Tue 19.0
# Wed 25.3
# Thu 17.8
# dtype: float64Creating a Series from a Dictionary
A Python dict can be passed directly to pd.Series(). The dict keys become the index labels and the values become the data. This is one of the most natural ways to create a Series when your data already has meaningful labels. The resulting Series is ordered by the dict's insertion order (Python 3.7+).
import pandas as pd
stock = {'AAPL': 182.5, 'GOOG': 141.3, 'MSFT': 378.9}
s = pd.Series(stock)
print(s)
# AAPL 182.5
# GOOG 141.3
# MSFT 378.9
# dtype: float64Creating a Series from a NumPy Array
A NumPy ndarray can be passed as the data argument. The dtype of the Series matches the ndarray's dtype. The underlying data is stored as a NumPy array, so all NumPy ufuncs work directly on Series. This makes it easy to migrate existing NumPy code to Pandas without rewriting data preparation logic.
import pandas as pd
import numpy as np
arr = np.linspace(0, 1, 5)
s = pd.Series(arr, index=['a', 'b', 'c', 'd', 'e'])
print(s)
# a 0.00
# b 0.25
# c 0.50
# d 0.75
# e 1.00The .index and .values Attributes
s.index returns the Index object containing the labels. s.values returns the underlying NumPy array of data values. Both are essential for interoperability: you can pass s.values to any NumPy function and convert the result back to a Series with the original index. s.dtype gives the data type of the values.
import pandas as pd
s = pd.Series([3, 1, 4], index=['x', 'y', 'z'])
print(s.index) # Index(['x', 'y', 'z'], dtype='object')
print(s.values) # [3 1 4]
print(s.dtype) # int64Series Name and Index Name
A Series can have a .name attribute describing what the values represent, and its index can have a .name attribute describing what the labels represent. These names appear in DataFrames when a Series is assigned to a column, and in plot labels. Set them with s.name = 'price' or at creation with name=.
import pandas as pd
s = pd.Series([1.2, 3.4, 5.6],
index=['a', 'b', 'c'],
name='measurement')
s.index.name = 'label'
print(s)
# label
# a 1.2
# b 3.4
# c 5.6
# Name: measurement, dtype: float64Creating a Scalar Series
Passing a single scalar value to pd.Series() with an explicit index creates a Series where every element equals that scalar. This is similar to NumPy's np.full() and is handy for creating constant baseline Series to subtract from or compare with a real data Series.
import pandas as pd
s = pd.Series(5, index=['a', 'b', 'c', 'd'])
print(s)
# a 5
# b 5
# c 5
# d 5
# dtype: int64Automatic Index Alignment
One of the most powerful features of Pandas Series is automatic index alignment. When you add two Series, Pandas aligns them by their labels before computing the result. If a label exists in one Series but not the other, the result at that label is NaN. This prevents silent off-by-one errors common with NumPy array operations.
import pandas as pd
a = pd.Series([1, 2], index=['x', 'y'])
b = pd.Series([10, 20], index=['y', 'z'])
print(a + b)
# x NaN
# y 12.0
# z NaNChecking Series Length and Shape
len(s) returns the number of elements. s.shape returns a tuple (n,) consistent with NumPy conventions. s.size is the same as len(s). Use these checks at the start of a pipeline to validate that your data loading produced the expected number of rows before proceeding with analysis.
import pandas as pd
s = pd.Series(range(10))
print(len(s)) # 10
print(s.shape) # (10,)
print(s.size) # 10
print(s.ndim) # 1Converting a Series to Other Types
You can convert a Series back to a Python list with s.tolist(), to a NumPy array with s.to_numpy() or s.values, and to a dict with s.to_dict(). These conversions are useful for interoperability with libraries that do not accept Pandas objects and for serialising results to JSON or CSV.
import pandas as pd
s = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
print(s.tolist()) # [10, 20, 30]
print(s.to_numpy()) # [10 20 30]
print(s.to_dict()) # {'a': 10, 'b': 20, 'c': 30}Series vs DataFrame Column
A single column of a DataFrame is a Series. When you access df['col'], Pandas returns a Series with the same index as the DataFrame. Conversely, a Series with a name can be inserted into a DataFrame as a column directly. Understanding this relationship helps you move fluidly between Series and DataFrame operations.
import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6]})
col = df['a'] # Series
print(type(col)) # <class 'pandas.core.series.Series'>
print(col.values) # [1 2 3]Quick Check
Test your understanding of creating Pandas Series from this lesson.
Lesson Recap
In this lesson you learned: a Series is a 1-D labelled array built on a NumPy ndarray, it can be created from lists, dicts, NumPy arrays, or scalars, and index alignment automatically handles label-based arithmetic between two Series. Next up we cover accessing Series elements by label with .loc and by position with .iloc.
常见问题解答
「创建 Series」课时是免费的吗?
是的 — 「创建 Series」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「创建 Series」这节课中我会学到什么?
从 Python 列表、字典和 NumPy 数组构建 Pandas Series,并查看其 index 和 values 属性。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「创建 Series」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。