栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pandas基础入门之数据选择

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pandas基础入门之数据选择

学会做数据选择(特定行列抽取)是用Pandas做数据分析的基本功。 1.行列表示方法
  • 用index表示行索引名称。
  • 用columns表示列索引名称。
2.切片表示方法,怎样定位到想要的位置。

单值方式,用索引来定位。

import pandas as pd
import  numpy as np

df=pd.Series([1,2,4],index=('a','b','c'))
print(df)
print(df['a'])
print(df[0])



out:
a    1
b    2
c    4
dtype: int64
1------>索引为'a'的值
1------->第1行的值
  • 连续方式。
import pandas as pd

import  numpy as np

df=pd.Series([1,2,4,7,8],index=('a','m','c','e','f'))
print(df)
print(df[0:3])-------->>区间是左闭右开,不能取到右边的值
print(df[-2:-1])------->>负值表示从后开始取数
print(df['a':'c'])------>>可以取到区间右边的值
print(df[:])---------->>表示取全部的数



out:
a    1
m    2
c    4
e    7
f    8
dtype: int64
a    1
m    2
c    4
dtype: int64
e    7
dtype: int64
a    1
m    2
c    4
dtype: int64
a    1
m    2
c    4
e    7
f    8
dtype: int64
  • 列表方式。将要取值的索引或者行数放在一个列表里面。
import pandas as pd

import  numpy as np

df=pd.Series([1,2,4,7,8],index=('a','m','c','e','f'))
print(df)
print(df[['m','e','f']])
print(df[[0,2,4]])



out:
a    1
m    2
c    4
e    7
f    8
dtype: int64
m    2
e    7
f    8
dtype: int64
a    1
c    4
f    8
dtype: int64
  • 布尔方式。
import pandas as pd

import  numpy as np

df=pd.Series([1,2,4,7,8],index=('a','m','c','e','f'))
print(df)
print(df[df==4])
print(df.isin([4,7]))



out:
a    1
m    2
c    4
e    7
f    8
dtype: int64
c    4
dtype: int64
a    False
m    False
c     True
e     True
f    False
dtype: bool
3.同时抽取行列的方法。
  • 索引名称函数 loc[] ,也就是说loc是根据index来索引,比如下边的df定义了一个index,那么loc就根据这个index来索引对应的行。
  • 索引位置函数 iloc[],iloc并不是根据index来索引,而是根据行号来索引,行号从0开始,逐次加1。
  • 索引名称函数 at[]

  • 索引位置函数 iat[]

import pandas as pd

import  numpy as np

df=pd.Series([1,2,4,7,8],index=('a','m','c','e','f'))
print(df)
print(df.loc['a':'c'])
print(df.loc[['e','f']])
print(df.iloc[0:2])-------->>左闭右开的区间
print(df.iloc[3])

print(df.at['e'])
print(df.iat[2])

out:
a    1
m    2
c    4
e    7
f    8
dtype: int64
a    1
m    2
c    4
dtype: int64
e    7
f    8
dtype: int64
a    1
m    2
dtype: int64
7

7-------->>对应的index是'e'
4-------->>对应的是第3行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/357345.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号