pandas切片学习
程序员文章站
2022-05-20 10:54:02
...
**pandas切片学习 **
(1)创建DataFrame
-df = pd.DataFrame({'age':[10,2,30,40], 'grade':[100.0,90.0,66.0,98.0], 'sex':['female','male','female','male']})
—
(2)打印DataFrame一些属性
df.dtypes
age int64
grade float64
sex object
dtype: object
----------------------
df.value #array型
[[10 100.0 'female']
[20 90.0 'male']
[30 66.0 'female']
[40 98.0 'male']]
----------------------
df.index
RangeIndex(start=0, stop=4, step=1)
----------------------
df.columns
Index(['age', 'grade', 'sex'], dtype='object')
----------------------
df
age grade sex
0 10 100.0 female
1 20 90.0 male
2 30 66.0 female
3 40 98.0 male
(3)切片
print(df.loc[1:3,['sex','grade']])#只允许列名操作
print(df.loc[1:3,'age':'sex'])
sex grade
1 male 90.0
2 female 66.0
3 male 98.0
age grade sex
1 20 90.0 male
2 30 66.0 female
3 40 98.0 male
print(df.iloc[1:3,1:2])#iloc与loc不同,依靠列序定位而非列名,iloc区间是前闭后开
# 结果
grade
1 90.0
2 66.0
print(df.at[1,'grade'])#定位到某个值
print(df.iat[1,1])
print(df.ix[[0,1]])#行选择
#结果
90.0
90.0
age grade sex
0 10 100.0 female
1 20 90.0 male
#df只能单独进行行选择或者列选择,列选择只能是列名
print(df[0:2])#行选择,前闭后开
#结果
age grade sex
0 10 100.0 female
1 20 90.0 male
print(df[['age','sex']])#列选择
#结果
age sex
0 10 female
1 20 male
2 30 female
3 40 male
本文来自 LY_ysys629 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/ly_ysys629/article/details/55224284?utm_source=copy