Pandas 数据选择
.loc.iloc.at.iat[].attr
标量:相对于矢量,只有大小没有方向的数值。比如 39.343434
向量:矢量,既有方向,也有大小的一组数值。数据表里的一行数据,或者一列数据都可以是向量。比如 DataFrame 中的一行或者一列
.loc
loc返回对象降维,dataframe->series->标量
切片端点包含
不同对象类型:
- series:
s.loc[indexer] - dataframe:
df.loc[row_indexer,column_indexer]
常用方式:
df.loc['a']a为 index label,此处输入不是索引的整数位置df.loc[['a', 'b', 'c']]df.loc[['a', 'b', 'c'], :]df.loc[['a', 'b', 'c'], ['A':]]s.loc[['a', 'b', 'c']]df.loc['b':]df.loc['b':'d']包括行
b和ddf.loc[:, 'B':'D']df.loc[:, ['B', 'D']]df.loc[df.A > 0]df.loc[df.index.isin(['a', 'b'])]df.loc[df.index == 'a']df.loc[(df['date'] > '2019-12') & (df['date'] < '2020-05')]df.loc[lambda x: x['date'] > '2019-12']df.loc[:, lambda df: ['A', 'B']]
.iloc
iloc返回对象降维,dataframe->series->标量
切片时,开始包括,而上限是排除
纯粹基于整数
不同对象类型:
- series:
s.iloc[indexer] - dataframe:
df.iloc[row_indexer,column_indexer]
常用方式:
df.iloc[3]df.iloc[1, 1]df.iloc[[3, 4, 5]]df.iloc[[3, 4, 5], :]df.iloc[4:]df.iloc[4:5]包含行4,不包含行5
df.iloc[:, 4:5]df.iloc[:, [4, 5]]df.iloc[[1, 3, 5], [1, 3]]df.iloc[[1, 3, 5], [1:3]]df.iloc[list(df.A<0)]或df.iloc[np.array(df.A<0)]df.iloc[df.index.isin(['a', 'c'])]df.loc[df.index == 'a']df.iloc[:, lambda df: [0, 1]]
.at 和 .iat
at 提供基于标签的标量查找,同时 iat 提供类似于基于整数的查找 iloc
df.at['b', 'B']df.iat[1, 1]
[]
只能输入一个维度,不能用逗号隔开输入两个维度
切片操作,语法与 ndarray 完全一样,返回值的一部分和相应的标签
s[:5]s[::-1]s[::2]df[:3]df[2:3]df[::-1]df[['A', 'B', 'D']]df['A']df[df.A<0]
.attr
用于访问列
df.A
布尔运算
必须使用括号进行分组
|&~
例如:
s[(s < -1) | (s > 0.5)]s[~(s < 0)]
isin
s.isin([2, 4, 6])s[s.index.isin([2, 4, 6])]s_mi.iloc[s_mi.index.isin([(1, 'a'), (2, 'b'), (0, 'c')])]
where
where 保证选择输出与原始数据具有相同的形状
In [16]: s
Out[16]:
4 0
3 1
2 2
1 3
0 4
dtype: int64
In [17]: s[s > 2]
Out[17]:
1 3
0 4
dtype: int64
In [18]: s.where(s > 2)
Out[18]:
4 NaN
3 NaN
2 NaN
1 3.0
0 4.0
dtype: float64