iloc函数根据行号/列号取值
loc函数根据行/列具体的值取值
# iloc取一行
data = pd.DataFrame(np.arange(16).reshape(4, 4),
index=['tony', 'andy', 'lucy', 'john'],
columns=['math', 'history', 'chemicy', 'english'])
data1 = data.iloc[0]
print('data1:', data1)
结果
data: math history chemicy english
tony 0 1 2 3
andy 4 5 6 7
lucy 8 9 10 11
john 12 13 14 15
data1: math 0
history 1
chemicy 2
english 3
Name: tony, dtype: int32
# iloc取多行
data2 = data.iloc[0:2]
print('data2:', data2)
结果
data2: math history chemicy english
tony 0 1 2 3
andy 4 5 6 7
# iloc取一列
data3 = data.iloc[:, 1]
print('data3:', data3)
结果:
data3: tony 1
andy 5
lucy 9
john 13
Name: history, dtype: int32
# iloc取多列
data4 = data.iloc[:, 1:3]
print('data4:', data4)
结果:
data4: history chemicy
tony 1 2
andy 5 6
lucy 9 10
john 13 14
# iloc取一行一列
data5 = data.iloc[1, 2]
print('data5:', data5)
结果:
data5: 6
# iloc取多行多列
data6 = data.iloc[0:2, 1:3]
print('data6:', data6)
结果:
data6: history chemicy
tony 1 2
andy 5 6
# iloc取所有行所有列
data66 = data.iloc[:, :]
print('data66:', data66)
结果:
data66: math history chemicy english
tony 0 1 2 3
andy 4 5 6 7
lucy 8 9 10 11
john 12 13 14 15
# loc取一行
data7 = data.loc['andy']
print('data7:', data7)
结果:
data7: math 4
history 5
chemicy 6
english 7
Name: andy, dtype: int32
# loc取多行
data8 = data.loc[['andy', 'john'], :]
print('data8:', data8)
结果:
data8: math history chemicy english
andy 4 5 6 7
john 12 13 14 15
# loc取一列
data9 = data.loc[:, 'chemicy']
print('data9:', data9)
结果:
data9: tony 2
andy 6
lucy 10
john 14
Name: chemicy, dtype: int32
# loc取多列
data10 = data.loc[:, ['english', 'history']]
print('data10:', data10)
结果:
data10: english history
tony 3 1
andy 7 5
lucy 11 9
john 15 13
# loc取一行一列
data11 = data.loc[['john'], ['history']]
print('data11:', data11)
结果:
data11: history
john 13
# loc取多行多列
data12 = data.loc[['andy', 'john'], ['english', 'history']]
print('data12:', data12)
结果:
data12: english history
andy 7 5
john 15 13
# loc取所有行所有列
data122 = data.loc[:, :]
print('data122:', data122)
结果:
data122: math history chemicy english
tony 0 1 2 3
andy 4 5 6 7
lucy 8 9 10 11
john 12 13 14 15