简单的可以分为两类,一类是单纯的行,列取子集(以索引筛选);另一类是筛选出符合要求的子集。先介绍简单的行列subset,后介绍条件筛选。
import pandas as pd
x = pd.DataFrame({'x1':[1,2,3],'x2':[4,5,6],'x3':[7,8,9]})
x
1.1 取单个列
返回的数据类型可能不同,要注意下。
print(x.x1);type(x.x1)
0 1
1 2
2 3
Name: x1, dtype: int64
pandas.core.series.Series
print(x["x1"]);type(x["x1"])
0 1
1 2
2 3
Name: x1, dtype: int64
pandas.core.series.Series
print(x[["x1"]]);type(x[["x1"]])
x1
0 1
1 2
2 3
pandas.core.frame.DataFrame
1.2 取多个列
print(x[["x1","x2"]])
x1 x2
0 1 4
1 2 5
2 3 6
x.loc[:,["x1","x2"]]
x.iloc[:,[0,1]]
1.3 取行
print(x.loc[0]);type(x.loc[0])
x1 1
x2 4
x3 7
Name: 0, dtype: int64
pandas.core.series.Series
print(x.loc[[0]]);type(x.loc[[0]])
x1 x2 x3
0 1 4 7
pandas.core.frame.DataFrame
print(x.loc[[0,2]]);type(x.loc[[0,2]])
x1 x2 x3
0 1 4 7
2 3 6 9
pandas.core.frame.DataFrame
1.4 同时取行和列
主要有两个函数可以用:loc、iloc。两者的区别在于:loc根据具体列名选取列;而iloc根据列所在位置/索引选取列,从0开始计数。
1.4.1 loc
x.loc[[0,2],['x1','x2']]
x.iloc[:,[1,2]]
1.5 条件过滤-根据值
根据一定的条件筛选出符合条件的数据,不知道能不能找到类似R里面subset的函数。
1.5.1 逻辑判断
x[(x.x2>4) & (x.x3<9)]
1.5.2 isin
x[x.x1.isin([2])]
1.5.3 where
where的语法有点怪,更像是ifelse的处理方式。
x.where(cond, other=nan, inplace=False, axis=None, level=None, try_cast=False, raise_on_error=True)
- cond为筛选条件,可以用把代码放在()中
- other不满足cond时怎么填补,默认NAN填充
- inplace为True时,改变原来数据对象(即other填充之后的数据覆盖原始数据),默认为False,不覆盖
- 其余参数不赘
x.where(x.x1 == 2,-x)
x.where(cond = (lambda x:x>2),other=(lambda x:x+10))
1.5.4 query
这个和R里subset比较接近,但是没有select的功能(即可选地保留最终想要的列)。等号要写成判断的形式"=="
x.query("x2>4 and x3<9")
1.6 条件过滤-根据索引
根据列名(column)or行名(index)进行数据筛选。
DataFrame.filter(items=None, like=None, regex=None, axis=None)
参考:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html
import pandas as pd
x = pd.DataFrame({'x1': [1, 2, 3], 'x2': [4, 5, 6], 'y1': [7, 8, 9]})
1.6.1 items选择
x.filter(items=['x1','x2'],axis = 1)
x.filter(items=[0,2],axis = 0)
1.6.2 regex正则匹配
x.filter(regex='^x',axis = 1)
x.filter(regex='^[02]',axis = 0)
1.6.3 like正则匹配
x.filter(like='y',axis = 1)
2018-10-13 于南京市栖霞区紫东创业园