目录

  • 1.索引是什么
    • 1.1 认识索引
    • 1.2 自定义索引
  • 2. 索引的简单使用
    • 2.1 列索引
      • 2.1.2 使用loc和iloc
    • 2.2 行索引
      • 2.2.1 使用[ : ]
      • 2.2.2 使用.loc()和.iloc()
  • 3. 根据列条件,选取dataframe数据框中的数据
  • 4. 根据列条件,获取行索引号并转成列表

总结一下 DataFrame索引问题

1.索引是什么

1.1 认识索引

先创建一个简单的DataFrame

myList = [['a', 10, 1.1],['b', 20, 2.2],['c', 30, 3.3],['d', 40, 4.4]]
df1 = pd.DataFrame(data = myList)
print(df1)
--------------------------------
[out]:0   1    2
0  a  10  1.1
1  b  20  2.2
2  c  30  3.3
3  d  40  4.4

DataFrame中有两种索引:

  • 行索引(index):对应最左边那一竖列
  • 列索引(columns):对应最上面那一横行

两种索引默认均为从0开始的自增整数。

# 输出行索引
print(df1.index)
[out]:
RangeIndex(start=0, stop=4, step=1)
---------------------------------------
# 输出列索引
print(df1.columns)
[out]:
RangeIndex(start=0, stop=3, step=1)
---------------------------------------
# 输出所有的值
print(df1.values)
[out]:
array([['a', 10, 1.1],['b', 20, 2.2],['c', 30, 3.3],['d', 40, 4.4]], dtype=object)

1.2 自定义索引

可以使用 index 这个参数指定行索引,columns 这个参数指定列索引。

df2 = pd.DataFrame(myList, index = ['one', 'two', 'three', 'four'], columns = ['char', 'int', 'float'])
print(df2)
-----------------------------------------------------------
[out]:char  int  float
one      a   10    1.1
two      b   20    2.2
three    c   30    3.3
four     d   40    4.4

输出此时的行索引和列索引:

# 输出行索引
print(df2.index)
[out]:
Index(['one', 'two', 'three', 'four'], dtype='object')
--------------------------------------------------------
# 输出列索引
print(df2.columns)
[out]:
Index(['char', 'int', 'float'], dtype='object')

2. 索引的简单使用

2.1 列索引

  • 选择一列:
print(df2['char'])
print(df2.char)
# 两种方式输出一样
[out]:
one      a
two      b
three    c
four     d
Name: char, dtype: object

注意此时方括号里面只传入一个字符串 ’char’,这样选出来的一列,结果的类型为 Series

type(df2['char'])
[out]: pandas.core.series.Series
  • 选择多列:
print(df2[['char', 'int']])
[out]: char   int
one      a   10
two      b   20
three    c   30
four     d   40

注意此时方括号里面传入一个列表 [‘char’, ‘int’],选出的结果类型为 DataFrame
如果只想选出来一列,却想返回 DataFrame 类型怎么办?

print(df2[['char']])
[out]:char
one      a
two      b
three    c
four     d
---------------------------------------
type(df2[['char']])
[out]:pandas.core.frame.DataFrame

注意直接使用 df2[0] 取某一列会报错,除非columns是由下标索引组成的,比如df1那个样子,df1[0] 就不会报错。

print(df1[0])
[out]:
0    a
1    b
2    c
3    d
Name: 0, dtype: object
-----------------------
print(df2[0])
[out]:
KeyError: 0

2.1.2 使用loc和iloc

df = dat_df.iloc[:, [0, 2, 3, 4]]  #选择所有行,并选择第0,2,3,4列,列名可以为其它字符串

2.2 行索引

2.2.1 使用[ : ]

区别于选取列,此种方式 [ ] 中不再单独的传入一个字符串,而是需要使用冒号切片。

  • 选取行标签从 ’two’’three’ 的多行数据
print(df2['two': 'three'])
[out]:char  int  float
two      b   20    2.2
three    c   30    3.3
# dataframe格式
# 也可以直接用数字
  • 选取行标签为 ’two’ 这一行数据
# 此时返回的类型为DataFrame
print(df2['two': 'two'])
[out]:char  int  float
two      b   20    2.2

[ ] 中不仅可以传入行标签,还可以传入行的编号。

  • 选取从第1行到第3行的数据(编号从0开始)
print(df2[1:4])
[out]:char  int  float
two      b   20    2.2
three    c   30    3.3
four     d   40    4.4
# dataframe格式

可以看到选取的数据是不包含方括号最右侧的编号所对应的数据的。

  • 选取第1行的数据
print(df2[1:2])
[out]:char  int  float
two    b   20    2.2

2.2.2 使用.loc()和.iloc()

区别就是 .loc() 是根据行索引和列索引的值来选取数据,而 .iloc() 是根据从 0 开始的下标位置来进行索引的。

  • 选取行:
    1. 使用.loc()
print(df2.loc['one'])
[out]:
char       a
int       10
float    1.1
Name: one, dtype: object
-------------------------------------------
print(df2.loc[['one', 'three']])
[out]:char  int  float
one      a   10    1.1
three    c   30    3.3
-------------------------------------------
df2.loc['one': 'three']
Out[14]: char  int  float
one      a   10    1.1
two      b   20    2.2
three    c   30    3.3

2. 使用.iloc()

print(df2.iloc[0])
[out]:
char       a
int       10
float    1.1
Name: one, dtype: object
-------------------------------------------
print(df2.iloc[[0, 2]])
[out]:char  int  float
one      a   10    1.1
three    c   30    3.3
-------------------------------------------
df2.iloc[1: 3]
Out[18]: char  int  float
two      b   20    2.2
three    c   30    3.3

3. 根据列条件,选取dataframe数据框中的数据

# 选取等于某些值的行记录 用 == df.loc[df['column_name'] == some_value]# 选取某列是否是某一类型的数值 用 isindf.loc[df['column_name'].isin(some_values)]# 多种条件的选取 用 &df.loc[(df['column'] == some_value) & df['other_column'].isin(some_values)]# 选取不等于某些值的行记录 用 !=df.loc[df['column_name'] != some_value]# isin返回一系列的数值,如果要选择不符合这个条件的数值使用~df.loc[~df['column_name'].isin(some_values)]

4. 根据列条件,获取行索引号并转成列表

dataframe中根据一定的条件,得到符合要求的某些行元素所在的位置

import pandas as pd
df = pd.DataFrame({'BoolCol': [1, 2, 3, 3, 4],'attr': [22, 33, 22, 44, 66]},  index=[10,20,30,40,50])
print(df)
a = df[(df.BoolCol==3)&(df.attr==22)].index.tolist()
print(a)

输出:

  BoolCol  attr
10        1    22
20        2    33
30        3    22
40        3    44
50        4    66
[30]

注意:
df[(df.BoolCol==3)&(df.attr==22)].index 返回的是 index 对象列表,需转换为普通列表格式时用 tolist() 方法

参考链接
[1] Pandas中DataFrame索引、选取数据 2020.3

python中Pandas之DataFrame索引、选取数据相关推荐

  1. Python中pandas检查dataframe中是否包含某个字段、或者数据列实战、检查dataframe中是否包含某个字段集合

    Python中pandas检查dataframe中是否包含某个字段.或者数据列(column)实战 目录 Python中pandas检查dataframe中是否包含某个字段.或者数据列(column) ...

  2. Python中通过索引名称提取数据loc()函数Python中通过行和列下标提取数据iloc()函数

    [小白从小学Python.C.Java] [Python全国计算机等级考试] [Python数据分析考试必会题] ● 标题与摘要 Python中通过索引名称提取数据 loc()函数 Python中通过 ...

  3. 怎么把竖列中的数相加python_关于python中pandas.DataFrame对行与列求和及添加新行与列示例代码...

    pandas是python环境下最有名的数据统计包,而DataFrame翻译为数据框,是一种数据组织方式,这篇文章主要给大家介绍了关于python中pandas.DataFrame对行与列求和及添加新 ...

  4. python中pandas的数据输出显示设置

    python中pandas的数据输出显示设置1 pandas数据分析时经常需要打印输出数据,当数据量大时,输出的展示设置非常重要,好的展示可以帮助更好地理解数据. pandas相关的显示设置函数主要有 ...

  5. Python中pandas库实现数据缺失值判断isnull()函数

    [小白从小学Python.C.Java] [Python全国计算机等级考试] [Python数据分析考试必会题] ● 标题与摘要 Python中pandas库实现数据缺失值判断 isnull()函数 ...

  6. python使用pandas计算dataframe中每个分组的分位数极差、分组数据的分位数极差(range)、使用groupby函数和agg函数计算分组的两个分位数

    python使用pandas计算dataframe中每个分组的分位数极差.分组数据的分位数极差(range).使用groupby函数和agg函数计算分组的两个分位数 目录

  7. python使用pandas计算dataframe中每个分组的极差、分组数据的极差(range)、使用groupby函数和agg函数计算分组的最大值和最小值

    python使用pandas计算dataframe中每个分组的极差.分组数据的极差(range).使用groupby函数和agg函数计算分组的最大值和最小值 目录

  8. pandas计算dataframe两列数据值相等的行号、取出DataFrame中两列值相等的行号

    pandas计算dataframe两列数据值相等的行号.取出DataFrame中两列值相等的行号 目录 pandas计算dataframe两列数据值相等的行号.取出DataFrame中两列值相等的行号

  9. series 合并pandas_在python中pandas的series合并方法

    如下所示: In [3]: import pandas as pd In [4]: a = pd.Series([1,2,3]) In [5]: b = pd.Series([2,3,4]) In [ ...

最新文章

  1. YOLO-v5训练自己的数据+TensorRT推理部署(2)
  2. Jenkins 流水线 获取git 分支列表_基于Jenkins的DevOps流水线实践课程
  3. 错误:请求“ ..”中的成员“ ..”属于非类类型
  4. python编程题-python编程题库
  5. Cocos2d-x 3.0正式版及android环境搭建
  6. 一、为了OFFER系列 | 阿里云天池赛在线编程:移动的圆
  7. VTK:Points之DensifyPoints
  8. EntityFramework Core 迁移忽略主外键关系
  9. mfc mysql 选择删除文件_MFC应用实例:[60]删除指定类型的文件
  10. kgtp linux内核调试
  11. 【实践】58同城本地服务推荐系统演进
  12. R爬虫小白入门:Rvest爬链家网+分析(三)
  13. PHP - XHProf简明教程
  14. 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  15. 计算机技术服务的增值税税率,咨询系统集成技术服务税率
  16. XXX@1.0.0 build: `NODE_ENV=production webpack --config webpack.config.js`报错的解决
  17. 动态代理[JDK]机制解析
  18. 流量从“海量”到“僵化”,精细化运营是企业最后一根救命稻草
  19. html+css学习第六天(背景图片、精灵图片、元素内容溢出、长度单位)
  20. 【ybt高效进阶1-5-2】【luogu P3456】山峰和山谷 / GRZ-Ridges and Valleys

热门文章

  1. excel连接mysql速度太慢,excel表格数据太大-excel太大,运行缓慢该怎么办
  2. katalon错误: System could not generate internal.GlobalVariable file normally.
  3. 计算机考研分数403,总分403分过来人分享成功考研经验_跨考网
  4. 微信小程序-百度AI语音识别——(一)
  5. >>技术开发:轻量级BI工具Superset
  6. oracle常用创建模式,ORACLE 常用操作命令
  7. Android体系架构及认识
  8. TIA博途中如何使用符号方式按位,字节,字访问非结构数据类型
  9. python报错“ImportError: The _imagingft C module is not installed”
  10. 基于PHP的学生宿舍管理系统