- From a one-dimensional
list
.
Example.
Create a
Series
from a
tuple
,
range
,
or
np.ndarray
the same way.
-
From a
list
of two-item
list
s.
The first column specifies the index.
Example.
-
From a
dict
.
The keys of the
dict
specify the index.
Example.
-
Create a
Series
holding multiple copies of the same value.
import sys
import numpy as np
import pandas as pd
#Series born holding 10 zeros.
#Must specify a range so the computer knows how many zeros.
series = pd.Series(data = 0, index = np.arange(10))
print(series)
sys.exit(0)
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
dtype: int64
-
Create an empty
Series
,
and then append rows to it.
import sys
import numpy as np
import pandas as pd
series = pd.Series(dtype = np.int64) #Start with an empty Series.
print(series)
print()
series.loc[0] = 10
print(series)
print()
s = pd.Series(data = [20, 30], index = [1, 2])
series = series.append(s)
print(series)
sys.exit(0)
Series([], dtype: int64)
0 10
dtype: int64
0 10
1 20
2 30
dtype: int64
-
Create a copy of an existing
Series
.
In the following program,
series0
and
series1
share the same data.
They are merely two different
views
of the same data.
import sys
import pandas as pd
series0 = pd.Series(data = [10, 20, 30], name = "series0")
print(series0)
print()
series1 = pd.Series(data = series0, name = "series1")
series1[0] = 11 #Warning: changes series0.
print(series0)
print()
series2 = series0.copy()
series2.name = "series2"
series2[1] = 21 #Does not change series0.
print(series0)
sys.exit(0)
0 10
1 20
2 30
Name: series0, dtype: int64
0 11
1 20
2 30
Name: series0, dtype: int64
0 11
1 20
2 30
Name: series0, dtype: int64
-
Read a
Series
from a text file containing one or two columns.
import sys
import pandas as pd
url = "http://oit2.scps.nyu.edu/~meretzkm/pandas/series/infile1.txt"
df = pd.read_csv(url, header = None) #Create a pd.DataFrame containing one column numbered 0
series = df[0] #Get that column.
print(series)
sys.exit(0)
0 10
1 20
2 30
3 40
4 50
Name: 0, dtype: int64
import sys
import pandas as pd
url = "http://oit2.scps.nyu.edu/~meretzkm/pandas/series/infile2.csv"
df = pd.read_csv(url, index_col = "day") #Create a pd.DataFrame containing one column named "temperature".
series = df["temperature"] #Get that column.
print(series)
sys.exit(0)
day
1 10.0
2 20.0
3 30.0
4 40.0
5 50.0
Name: temperature, dtype: float64