Créer une Series
Créez une Series Pandas à partir d’une liste Python, d’un dictionnaire et d’un tableau NumPy, puis examinez ses attributs d’index et de valeurs.
Créer une Series est une leçon Pandas & NumPy Academy gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Pandas & NumPy Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Pandas & NumPy Academy comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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.
Questions Fréquemment Posées
La leçon « Créer une Series » est-elle gratuite ?
Oui — le texte complet de « Créer une Series » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Pandas & NumPy Academy, passe à CoddyKit PRO. Le cours Pandas & NumPy Academy comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Créer une Series » ?
Créez une Series Pandas à partir d’une liste Python, d’un dictionnaire et d’un tableau NumPy, puis examinez ses attributs d’index et de valeurs. Tu pratiques Pandas & NumPy Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Pandas & NumPy Academy ?
Aucune expérience préalable n'est requise. Pandas & NumPy Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Créer une Series » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Pandas & NumPy Academy ?
Oui. Chaque leçon Pandas & NumPy Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Créer une Series
- Accès par étiquette et par position
- Opérations vectorisées sur les Series
- Méthodes utiles des Series