程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(5)

Pandas各种方式读取dataframe的数据,有这篇就够了

发布于2020-02-25 01:00     阅读(1358)     评论(0)     点赞(9)     收藏(1)


######  loc只能通过index和columns的名称来取,不能用数字
########iloc只能用数字索引,不能用索引名
  1. import numpy as np
  2. from pandas import DataFrame
  3. import pandas as pd
  4. #构建dataframe,二维数组
  5. df = DataFrame(np.arange(20).reshape(4,5),index=['one','two','three','four'],columns=list('abcde'))
  6. print(df)

        a   b   c   d   e
one     0   1   2   3   4
two     5   6   7   8   9
three  10  11  12  13  14
four   15  16  17  18  19

  1. ############### 1.获取指定列的数据######
  2. print("获取指定的某列:")
  3. print(df['a'])
  4. #注意双[]
  5. print(df[['a','b']])

获取指定的某列:
one       0
two       5
three    10
four     15
Name: a, dtype: int32
        a   b
one     0   1
two     5   6
three  10  11
four   15  16

  1. ############### 2.获取指行的数据######
  2. print("获取指行的某行:")
  3. print(df.loc['one'])
  4. print(df.iloc[0:1])

获取指行的某行:
a    0
b    1
c    2
d    3
e    4
Name: one, dtype: int32
     a  b  c  d  e
one  0  1  2  3  4

  1. ############### 3.loc获取指某行某列的数据######
  2. ###### loc只能通过index和columns的名称来取,不能用数字
  3. print("loc获取指定某行某列的数据")
  4. print(df.loc['one','c'])
  5. #获取行索引one到three,列索引a到d的数据
  6. print(df.loc['one':"three","a":'d'])
  7. #获取行索引one到three,列索引a,d的数据
  8. print(df.loc['one':'three',['a','d']])
  9. #获取行索引one,three,列索引a,d的数据
  10. print(df.loc[['one','three'],['a','d']])

loc获取指定某行某列的数据
2


        a   b   c   d
one     0   1   2   3
two     5   6   7   8
three  10  11  12  13


        a   d
one     0   3
two     5   8
three  10  13


        a   d
one     0   3
three  10  13

  1. ############### 4.iloc获取指某行某列的数据######
  2. ########iloc只能用数字索引,不能用索引名
  3. print("iloc获取指定某行某列的数据")
  4. print(df.iloc[0:1,2:3])
  5. #获取行索引one到three,列索引a到d的数据
  6. print(df.iloc[0:4,0:4])
  7. #获取行索引one到three,列索引a,d的数据
  8. print(df.iloc[0:4,[0,3]])
  9. #获取行索引one,three,列索引a,d的数据
  10. print(df.iloc[[0,2],[0,3]])

iloc获取指定某行某列的数据
     c
one  2


        a   b   c   d
one     0   1   2   3
two     5   6   7   8
three  10  11  12  13
four   15  16  17  18


        a   d
one     0   3
two     5   8
three  10  13
four   15  18


        a   d
one     0   3
three  10  13

  1. ############### 5.获取具体某个单值######
  2. #iat取某个单值,只能数字索引
  3. #at取某个单值,只能index和columns索引
  4. print(df.iat[0,1])
  5. print(df.at['one','b'])

1
1
 

发布了448 篇原创文章 · 获赞 50 · 访问量 24万+


所属网站分类: 技术文章 > 博客

作者:嘴巴嘟嘟

链接:https://www.pythonheidong.com/blog/article/233087/f3c4ea7c7365a47fe150/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

9 0
收藏该文
已收藏

评论内容:(最多支持255个字符)