Convert a DataFrame row or column to a Series in pandas (or how to use iloc)
You can convert a DataFrame row to a Series using iloc
.
import pandas
csv = pandas.read_csv('a.csv')
print(csv)
# name age
# 0 Josh 27
# 1 Kyle 53
# 2 Bob 48
a = csv.iloc[0]
b = csv.iloc[1]
print(a)
# name Josh
# age 27
# Name: 0, dtype: object
print(b)
# name Kyle
# age 53
# Name: 1, dtype: object
print(type(a)) # <class 'pandas.core.series.Series'>
Convert a column to a Series
import pandas
csv = pandas.read_csv('a.csv')
print(csv)
# name age
# 0 Josh 27
# 1 Kyle 53
# 2 Bob 48
a = csv.iloc[:, 0]
b = csv.iloc[:, 1]
print(a)
# 0 Josh
# 1 Kyle
# 2 Bob
# Name: name, dtype: object
print(b)
# 0 27
# 1 53
# 2 48
# Name: age, dtype: int64
print(type(a)) # <class 'pandas.core.series.Series'>
Some articles shows to use ix
but iloc
should be used in pandas 1.1.3.