Pandas 数据框增、删、改、查、去重、抽样基本操作

转自:https://blog.csdn.net/claroja/article/details/65661826

总括
pandas的索引函数主要有三种: 
loc 标签索引,行和列的名称 
iloc 整型索引(绝对位置索引),绝对意义上的几行几列,起始索引为0 
ix 是 iloc 和 loc的合体 
at是loc的快捷方式 
iat是iloc的快捷方式

建立测试数据集:

import pandas as pd
df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c'],'c': ["A","B","C"]})
print(df)

行操作
选择某一行
print(df.loc[1,:])

选择多行
print(df.loc[1:2,:])#选择1:2行,slice为1
 
print(df.loc[::-1,:])#选择所有行,slice为-1,所以为倒序
  
print(df.loc[0:2:2,:])#选择0至2行,slice为2,等同于print(df.loc[0:2:2,:])因为只有3行

条件筛选
普通条件筛选
print(df.loc[:,"a"]>2)#原理是首先做了一个判断,然后再筛选

Name: a, dtype: bool

另外条件筛选还可以集逻辑运算符 | for or, & for and, and ~for not

In [129]: s = pd.Series(range(-3, 4))
In [132]: s[(s < -1) | (s > 0.5)]

isin
非索引列使用isin
In [141]: s = pd.Series(np.arange(5), index=np.arange(5)[::-1], dtype='int64')
In [143]: s.isin([2, 4, 6])
 

In [144]: s[s.isin([2, 4, 6])]

索引列使用isin
In [145]: s[s.index.isin([2, 4, 6])]

# compare it to the following
In [146]: s[[2, 4, 6]]

结合any()/all()在多列索引时
In [151]: df = pd.DataFrame({'vals': [1, 2, 3, 4], 'ids': ['a', 'b', 'f', 'n'],
   .....:                    'ids2': ['a', 'n', 'c', 'n']})
   .....: 
In [156]: values = {'ids': ['a', 'b'], 'ids2': ['a', 'c'], 'vals': [1, 3]}

In [157]: row_mask = df.isin(values).all(1)

In [158]: df[row_mask]

where()
In [1]: dates = pd.date_range('1/1/2000', periods=8)

In [2]: df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])

In [3]: df

In [162]: df.where(df < 0, -df)

DataFrame.where() differs from numpy.where()的区别

In [172]: df.where(df < 0, -df) == np.where(df < 0, df, -df)

当series对象使用where()时,则返回一个序列

In [141]: s = pd.Series(np.arange(5), index=np.arange(5)[::-1], dtype='int64')
In [159]: s[s > 0]
In [160]: s.where(s > 0)

抽样筛选
DataFrame.sample(n=None, frac=None, replace=False, weights=None, random_state=None, axis=None) 
当在有权重筛选时,未赋值的列权重为0,如果权重和不为1,则将会将每个权重除以总和。random_state可以设置抽样的种子(seed)。axis可是设置列随机抽样。

In [105]: df2 = pd.DataFrame({'col1':[9,8,7,6], 'weight_column':[0.5, 0.4, 0.1, 0]})

In [106]: df2.sample(n = 3, weights = 'weight_column')

增加行
df.loc[3,:]=4

插入行
pandas里并没有直接指定索引的插入行的方法,所以要自己设置

line = pd.DataFrame({df.columns[0]:"--",df.columns[1]:"--",df.columns[2]:"--"},index=[1])
df = pd.concat([df.loc[:0],line,df.loc[1:]]).reset_index(drop=True)#df.loc[:0]这里不能写成df.loc[0],因为df.loc[0]返回的是series

交换行
df.loc[[1,2],:]=df.loc[[2,1],:].values

删除行
df.drop(0,axis=0,inplace=True)

注意
在以时间作为索引的数据框中,索引是以整形的方式来的。

In [39]: dfl = pd.DataFrame(np.random.randn(5,4), columns=list('ABCD'), index=pd.date_range('20130101',periods=5))


列操作
更改列名
df.columns = df.columns.str.strip() # 把columns当成series看待 
df.columns = df.columns.map(lambda x:x) # 使用map函数 
df.rename(columns={’s’:’c’}, inplace=True)

选择某一列
print(df.loc[:,"a"])

选择多列
print(df.loc[:,"a":"b"])

增加列,如果对已有的列,则是赋值
df.loc[:,"d"]=4

交换两列的值
df.loc[:,['b', 'a']] = df.loc[:,['a', 'b']].values
print(df)

删除列
1)直接del DF[‘column-name’]

2)采用drop方法,有下面三种等价的表达式:

DF= DF.drop(‘column_name’, 1);

DF.drop(‘column_name’,axis=1, inplace=True)

DF.drop([DF.columns[[0,1,]]], axis=1,inplace=True)

df.drop("a",axis=1,inplace=True)
print(df)
 
还有一些其他的功能: 
切片df.loc[::,::] 
选择随机抽样df.sample() 
去重.duplicated() 
查询.lookup
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值