想要取DataFrame某行某列的操作
import pandas as pd
import numpy as np
#构筑数据
a = [np.random.randint(10,20) for i in range(7)]
b = ['a','b','c','d','e','f','g']
df = pd.DataFrame(a,index=b,columns=['name'])
df['name2'] = [np.random.randint(10,20) for i in range(7)]
生成结果。
#取已知index的某一行数据:
df.loc[a]
#取未知index某一行的数据:
df[1:2]#括号下包含,如取第二行数据则为应为[1:2]
#取未知index某N行的数据:
df[0:10]
#取已知名称的某一列:
df['name']
#取不知名称,但知道第几列的数据:
df.iloc[:,2]
#取已知名称的N列:
df[['name','name2']]
#取已知名称的N行M列:
df['name'][0:4]
#取不知名称的N行M列:
df.iloc[0:N,0:M]
#iloc是只取索引值即只取数值。loc取得是index索引值,和列名字。如数据中索引值有重复的情况,loc会报错。不使用loc和iloc则是选择第几行的指定名称的列。