通过给定的整数索引选择系列或数据框架的某一行
在Python中,Dataframe.iloc[]用于通过给定的整数索引来选择Series/Dataframe的某一行。
创建数据框架,通过索引选择行
在这里,我们正在创建一个带有ID、产品、价格、颜色和折扣的Pandas数据框架,其中有一些值。
# import pandas library
import pandas as pd
# Create the dataframe
df = pd.DataFrame({'ID': ['114', '345',
'157788', '5626'],
'Product': ['shirt', 'trousers',
'tie', 'belt'],
'Price': [1200, 1500,
600, 352],
'Color': ['White','Black',
'Red', 'Brown'],
'Discount': [10, 10,
10, 10]})
# Show the dataframe
df
输出:
只选择第一行
在这里,我们使用iloc选择第一行,Dataframe.iloc[]方法是在数据框的索引标签是数字系列以外的东西时使用。
# select first row
# from the dataframe
df.iloc[0]
输出:
选择0、1、2行
这里,我们使用iloc[0:3]选择第一第二和第三行,从0索引开始,以(3-1=2)索引结束。
# select 0, 1, 2 rows
#from the dataframe
df.iloc[0 : 3]
输出:
选择从0到2的行和从0到1的列
这里,我们使用iloc[0:3]选择第一第二第三行,以及第一和第二列。
# selecting rows from 0 to
# 2 and columns 0 to 1
df.iloc[0 : 3, 0 : 2]
输出:
选择所有行和第二列
从数据框架中选择所有的行,只选择第二列。
# selecting all rows and
# 3rd column
df.iloc[ : , 2]
输出:
选择从0到3的所有行和列
选择所有的行和列。
# selecting all rows and
# columns from 0 to 3
df.iloc[ : , 0 : 4]
输出: