前言: 已有一个pandas类型的data,通过np.where()
操作data,返回一个<class 'tuple'>
的select_data,元组的第一或第二个元素是我们想要的索引数组,假设索引数组(select_data[0] or select_data[1])命名为y,y的类型是<class 'numpy.ndarray'>
目的:直接取出索引数组对应的值
方法:
情况1:若data的类型是<class 'pandas.core.series.Series'>
,可以直接通过data[y]
获取索引数组对应的值数组;
情况2:若data类型是<class 'pandas.core.frame.DataFrame'>
,但它是一维(一行)数据,可使用:data = data.iloc[0]
iloc[0]取出DataFrame的第一行数据,返回的是一个Series对象,(然后使用data[y]
就可以啦~ )
情况3:若data类型是多维的<class 'pandas.core.frame.DataFrame'>
,目前俺还没有啥好办法欸~ 泥萌有啥好办法可以分享一下~
补充:
- iloc使用标量整数
print(type(df.iloc[0]))
提取行,返回Series类型 - iloc使用整数列表
print(type(df.iloc[[0]]))
df.iloc[[0, 2], [1, 3]]
等 提取行,返回DataFrame类型。 - iloc使用切片
df.iloc[1:3, 0:3]
,返回的也是dataframe
- iloc: works on the positions in the index (so it only takes integers). (位置索引,和列表索引类似,里面只能是数字)
- loc: works on labels in the index.(说白了就是标签索引)
(我理解的是:通过行名定位,所以可以是字符串)
- pandas以类似字典的方式来获取某一列的值,比如df[‘A’],得到df的A列,返回的也是一个Series对象
data.at[user_id,movie_name]
根据指定行 index(int) 及 列 label(str) 定位元素