pandas中DataFrame的查询

本文详细介绍了使用Python的Pandas库进行数据操作的方法,包括如何创建DataFrame,以及如何通过切片、loc、iloc、at和iat等函数进行数据选择和访问。通过实例展示了行和列的选择,以及单个元素的访问技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import pandas as pd
import numpy as np
arr = np.random.randn(3,3)

arr
array([[-0.4840499 , -1.10358516, -2.02087998],
       [ 1.47393252, -0.64985477, -0.11712859],
       [-0.44069225, -0.37788616,  0.56497586]])
df = pd.DataFrame(arr,index=('a','b','c'),columns=('A','B','C'))
df
ABC
a1.4403450.7022221.268813
b0.2689860.954185-0.273460
c-1.1879530.7177540.083791

[ ]切片方法

#行选择
df['a':'b']
ABC
a1.4403450.7022221.268813
b0.2689860.954185-0.273460
#列选择
df[['A','C']]
AC
a1.4403451.268813
b0.268986-0.273460
c-1.1879530.083791
#行列选择
df['b':'c'][['B','C']]
BC
b0.954185-0.273460
c0.7177540.083791

loc函数(使用索引值)

#行选择
df.loc['a':'b']
ABC
a1.4403450.7022221.268813
b0.2689860.954185-0.273460
#列选择
df.loc[:,['A','C']]
AC
a1.4403451.268813
b0.268986-0.273460
c-1.1879530.083791
#行列选择
df.loc['a':'b',['B','C']]
BC
a0.7022221.268813
b0.954185-0.273460

iloc函数(使用索引位置)

#行选择
df.iloc[0:1]
ABC
a1.4403450.7022221.268813
df.iloc[[0]]
ABC
a1.4403450.7022221.268813
#列选择
df.iloc[:,0:1]
A
a1.440345
b0.268986
c-1.187953
#行列选择
df.iloc[0:2,0:2]
AB
a1.4403450.702222
b0.2689860.954185

at函数(使用索引值访问单个元素)

df.at['a','A']
1.4403454841699048

iat函数(使用索引位置访问单个元素)

df.iat[0,0]
1.4403454841699048

ix函数(loc与iloc的混合)

df.ix[0:2,'A':'C']
/Users/f7689781/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
  """Entry point for launching an IPython kernel.
ABC
a-0.484050-1.103585-2.020880
b1.473933-0.649855-0.117129

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值