Pandas中DataFrame索引、选取数据

这是一篇最基础的Pandas用法总结,也方便自己日后进行复习与查询。
上一篇文章总结了Series索引问题。今天这篇来总结一下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.2 行索引
2.2.1 使用[ ]

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

  • 选取行标签从’two’到’three’的多行数据
print(df2['two': 'three'])
[out]:
      char  int  float
two      b   20    2.2
three    c   30    3.3
  • 选取行标签为’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

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

  • 选取第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
  1. 使用.iloc()
print(df2.iloc[0])
[out]:
char       a
int       10
float    1.1
Name: one, dtype: object

可以看到以上返回的结果都是Series。

  • 选取多行
  1. 使用.loc()
print(df2.loc[['one', 'three']])
[out]:
      char  int  float
one      a   10    1.1
three    c   30    3.3
  1. 使用.iloc()
print(df2.iloc[[0, 2]])
[out]:
      char  int  float
one      a   10    1.1
three    c   30    3.3

同理,如果想以DataFrame的类型选出某一行,需要传入只包含一个元素的列表:

print(df2.loc[['one']])
[out]:
    char  int  float
one    a   10    1.1

3. 索引的复杂使用

到目前位置,我们在选取数据时都只传入了一个维度的参数。既然有了行索引和列索引两个维度,就可以把它们组合起来使用。

df = pd.DataFrame([['F',22, 90],['M',32, 75],['F',18, 82],['M',14, 93]], 
                  columns=['gender','age', 'score'], 
                  index = ['小红', '小亮', '小兰', '小明'])
print(df)
[out]:
     gender  age  score
小红      F   22     90
小亮      M   32     75
小兰      F   18     82
小明      M   14     93
3.1 使用.loc()和.iloc()切片

取所有行,某列

# 取所有行,一列
df.loc[:, 'age']
df.iloc[:, 1]
[out]:
小红    22
小亮    32
小兰    18
小明    14
Name: age, dtype: int64

# 取所有行,多列
df.loc[:, ['age', 'gender']]
df.iloc[:, [1, 0]]
[out]:
      age gender
小红   22      F
小亮   32      M
小兰   18      F
小明   14      M

# 取所有行,前两列
df.loc[:, :'age']
df.iloc[:, :2]
[out]:
     gender  age
小红      F   22
小亮      M   32
小兰      F   18
小明      M   14

取某行,所有列

# 取一行,所有列
df.loc['小兰', :]
df.iloc[2, :]
[out]:
gender     F
age       18
score     82
Name: 小兰, dtype: object

# 取多行,所有列
df.loc[['小红', '小明'], :]
df.iloc[[0, 3], :]
[out]:
     gender  age  score
小红      F   22     90
小明      M   14     93

# 取前两行,所有列
df.loc[:'小亮', :]
df.iloc[:2, :]
[out]:
     gender  age  score
小红      F   22     90
小亮      M   32     75

取某行,某列

# 取前3行,第2到3列
df.iloc[:3, 1:3]
[out]:
     age  score
小红   22     90
小亮   32     75
小兰   18     82

# 取第2和第4行,前两列(不包含编号为2的列)
df.iloc[[1, 3], :2]
[out]:
     gender  age
小亮      M   32
小明      M   14

取某个位置的特定元素

# 取特定行列的元素
df.loc['小红', 'age']
df.iloc[0, 1]
[out]:
22
3.2 使用布尔索引切片

布尔值:

df['gender'] == 'M'
[out]:
小红    False
小亮     True
小兰    False
小明     True
Name: gender, dtype: bool

选出性别为’M’的所有行:

df.loc[df['gender']=='M', :] 
df[df['gender']=='M'] 
[out]:
     gender  age  score
小亮      M   32     75
小明      M   14     93
  • 68
    点赞
  • 192
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值