from pandas import Series,DataFrame
import pandas as pd
import numpy as np
df1=DataFrame(np.random.randint(0,10,(4,4)),index=['haha','dada','pipi','keke'],columns=['a','b','c','d'])print(df1)#使用loc获取第二行第三列的值print('使用loc获取第二行第三列的值:',df1.loc['dada','c'])#若使用位置索引,会报错,错误的演示:print(df1.loc[1,2])
#使用loc获取第三行的值print(df1.loc['pipi'])
》结果
a 7
b 3
c 9
d 8#使用loc获取第二三列的数据print(df1.loc[:,['b','c']])
》结果
b c
haha 39
dada 74
pipi 39
keke 26#使用loc获取第一二行及第三四列交叉的数据print(df1.loc[['haha','pipi'],['c','d']])
》结果
c d
haha 93
pipi 98
iloc
#使用iloc同理#iloc获取第二行的数据print(df1.iloc[1])
》结果
a 9
b 7
c 4
d 9
Name: dada, dtype: int32
#iloc获取第二列的数据print(df1.iloc[:,[1]])
》结果
b
haha 3
dada 7
pipi 3
keke 2
#使用get_value获取某个值,可以得到结果但是会告警,建议使用.atprint(df1.get_value('dada','c'))
》结果
4#FutureWarning: get_value is deprecated and will be removed in a future release. Please use .at[] or .iat[] accessors instead print(df1.get_value('dada','c'))