dataframe设置两个条件取值的实例

yipeiwu_com5年前Python基础

如下所示:

>>> import pandas as pd
>>> import numpy as np
>>> from pandas import Series, DataFrame
>>> df = DataFrame({'name':['a','a','b','b'],'classes':[1,2,3,4],'price':[11,22,33,44]})
>>> df
 classes name price
0  1 a  11
1  2 a  22
2  3 b  33
3  4 b  44
>>> 

根据index和columns取值

>>> s = df.loc[0,'price']
>>> s
11

根据同行的columns的值取同行的另一个columns的值

>>> sex = df.loc[(df.classes==1)&(df.name=='a'),'price']
>>> sex
0 11
Name: price, dtype: int64
>>> sex = df.loc[(df.classes==1)&(df.name=='a'),'price'].values[0]
>>> sex
11

根据条件同时取得多个值

>>> name,price = df.loc[df.classes==1,('name','price')].values[0]
>>> name
'a'
>>> price
11
>>>

对一列赋值

>>> df.loc[: , 'price']=0
>>> df
 classes name price
0  1 a  0
1  2 a  0
2  3 b  0
3  4 b  0
>>>

对df的一个列进行函数运算

【1】
>>> df['name'] = df['name'].apply(lambda x: x.upper())
>>> df
 classes name price
0  1 A  11
1  2 A  22
2  3 B  33
3  4 B  44
【2】
>>> df.loc[:, 'name'] = df['name'].apply(lambda x: x.upper())
>>> df
 classes name price
0  1 A  11
1  2 A  22
2  3 B  33
3  4 B  44
>>>

对df的几个列进行函数运算

【1】
>>> df[['classes','price']] = df[['classes', 'price']].applymap(lambda x: str(x))
>>> print(type(df.loc[0, "classes"]))
<class 'str'>
>>> print(df.loc[0, "classes"])
1
【2】
>>> df.loc[:, ['classes','price']] = df[['classes', 'price']].applymap(lambda x: int(x))
>>> print(type(df.loc[0, "classes"]))
<class 'int'>
>>> print(df.loc[0, "classes"])
1
>>> 

对两个列进行去重

>>> df
 classes name price
0  1 a  11
1  1 a  22
2  3 b  33
3  4 b  44
>>> df.drop_duplicates(subset=['classes', 'name'], inplace=True)
>>> df
 classes name price
0  1 a  11
2  3 b  33
3  4 b  44

多个条件分割字符串

>>> fund_memeber = '赵四、 王五'
>>> fund_manager_list = re.split('[;, 、]', fund_memeber)
>>> fund_manager_list
['赵四', '', '王五']
#DataFrame构造器
>>> df = DataFrame({'x':[1],'y':[2]})
>>> df
 x y
0 1 2
>>>

删除某列值为特定值得那一行

>>> df = DataFrame({'name':['a','b','c','d'],'classes':[1,2,3,4],'price':[11,22,33,44]})
>>> df
 classes name price
0  1 a  11
1  2 b  22
2  3 c  33
3  4 d  44
【方法一】
>>> df = df.loc[df['name']!='a']
>>> df
 classes name price
1  2 b  22
2  3 c  33
3  4 d  44
>>> 
【方法二】
 df.drop(df[df.name=='a'].index,axis=0)
 #筛选df的每列值包含某个字段‘/a'
 >>> import pandas as pd
>>> df = pd.DataFrame({'a':['A', 'B'], 'b': ['AA', 'BB']})
>>> df
 a b
0 A AA
1 B BB
>>> df[df['a'].str.contains(r'A')]
 a b
0 A AA
>>> df = pd.DataFrame({'a':['/api/', 'B'], 'b': ['AA', 'BB']})
>>> df
  a b
0 /api/ AA
1  B BB
>>> df[df['a'].str.contains(r'/api/')]
  a b
0 /api/ AA
>>>

把列变成index和把index变成列

df
  request_url visit_times
9 fofeasy_产品基本信息   7
8   投顾挖掘   6
5   投顾挖掘   5
6   投顾挖掘   5
7 fofeasy_产品基本信息   5
3 fofeasy_产品基本信息   4
4 fofeasy_产品基本信息   4
2   投顾挖掘   2
0  行业数据——其他   1
1  行业数据——其他   1
x = df.set_index('request_url')
x
    visit_times
request_url    
fofeasy_产品基本信息   7
投顾挖掘      6
投顾挖掘      5
投顾挖掘      5
fofeasy_产品基本信息   5
fofeasy_产品基本信息   4
fofeasy_产品基本信息   4
投顾挖掘      2
行业数据——其他     1
行业数据——其他     1
x.reset_index('request_url')
  request_url visit_times
0 fofeasy_产品基本信息   7
1   投顾挖掘   6
2   投顾挖掘   5
3   投顾挖掘   5
4 fofeasy_产品基本信息   5
5 fofeasy_产品基本信息   4
6 fofeasy_产品基本信息   4
7   投顾挖掘   2
8  行业数据——其他   1
9  行业数据——其他   1

pandas 按照列A分组,将同一组的列B求和,生成新的Dataframe

>>>df.groupby(by=['request_url'])['visit_times'].sum()
>>>
request_url
fofeasy_产品基本信息 20
投顾挖掘    18
行业数据——其他   2
Name: visit_times, dtype: int64

dict变成dataframe

In [15]: dict = pd.DataFrame({'x':1, 'y':2}, index=[0])
In [16]: dict
Out[16]:
 x y
0 1 2

iloc

In [69]: df1.iloc[1:5, 2:4]
Out[69]: 
   4   6
2 0.301624 -2.179861
4 1.462696 -1.743161
6 1.314232 0.690579
8 0.014871 3.357427

以上这篇dataframe设置两个条件取值的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

对python 多线程中的守护线程与join的用法详解

多线程:在同一个时间做多件事 守护线程:如果在程序中将子线程设置为守护线程,则该子线程会在主线程结束时自动退出,设置方式为thread.setDaemon(True),要在thread....

Python中的Numeric包和Numarray包使用教程

要了解 Numerical Python 软件包的第一件事情是,Numerical Python 不会让您去做标准 Python 不能完成的任何工作。它只是让您 以快得多的速度去完成标准...

Python对HTML转义字符进行反转义的实现方法

Python对HTML转义字符进行反转义的实现方法

什么是转义字符 在 HTML 中 <、>、& 等字符有特殊含义(<,> 用于标签中,& 用于转义),他们不能在 HTML 代码中直接使用,如果要在网页中显示这些...

基于Python的图像数据增强Data Augmentation解析

基于Python的图像数据增强Data Augmentation解析

1.1 简介 深层神经网络一般都需要大量的训练数据才能获得比较理想的结果。在数据量有限的情况下,可以通过数据增强(Data Augmentation)来增加训练样本的多样性, 提高模型鲁...

python 导入数据及作图的实现

我们经常需要导入数据,按列提取 XY作图 方法一、 filename='/home/res/user/csluo/test.txt' #将文件名赋值为变量 X,...