python pandas遍历每行并累加进行条件过滤方式

作者:向日葵 时间:2023-08-07 12:41:54 

pandas遍历每行并累加进行条件过滤

python pandas遍历每行并累加进行条件过滤方式

 本次记录主要实现对每行进行排序,并保留前80%以前的偏好。

思路:

将每行的概率进行排序,然后累加,累加值小于等于0.8的偏好保留,获得一个累加过滤的dataframe,然后映射回原始数据中,保留每行的偏好。接下来是代码的实现

a = [[0.2, 0.35, 0.45], [0.1,0.2, 0.7], [0.3, 0.5, 0.2]]
data = pd.DataFrame(a, index=['user1','user2','user3'], columns=["a", "b", "c"])
sum_df=[]
for index,row in data.iterrows():
   df = row.sort_values(ascending=False).cumsum()
   if df[0]>0.8:
       new_df = df[:1]
   else:
       new_df = df[df<=0.8]
   sum_df.append(new_df)
sum_df = pd.DataFrame(sum_df)
print(sum_df)

python pandas遍历每行并累加进行条件过滤方式

这是累加之后每个用户保留的前80%偏好的类型,接下来如何将这个特征映射回去,将累加后的dataframe通过空值将其转化为0-1dataframe,再和原数据集一一对应相乘,就可以映射回去了,代码如下

d = (sum_df.notnull())*1
print(d)

python pandas遍历每行并累加进行条件过滤方式

final_df = d*data #将保留地特征映射到原始数据中
print(final_df)

python pandas遍历每行并累加进行条件过滤方式

本节内容目标明确,实现了每个用户的前80%偏好,不知道正在看的小伙伴有没有懂?可以一起讨论哦!

接下来,考虑优化这个实现的代码,前面的思路是通过两个dataframe相乘实现的,当数据集非常大的时候,效率很低,于是不用list,利用字典的形式实现

sum_df=[]
for index,row in data.iterrows():
   df = row.sort_values(ascending=False).cumsum()
   origin = row.to_dict() #原始每个用户值
   if df[0]>0.8:
       new_df = df[:1]
   else:
       new_df = df[df<=0.8]
   name = new_df.name  #user
   tmp = new_df.to_dict()
   for key in tmp.keys(): # 原始值映射
       tmp[key] = origin[key]
   tmp['user'] = name
   sum_df.append(tmp)
sum_df = pd.DataFrame(sum_df).set_index('user').fillna(0)
print(sum_df)

python pandas遍历每行并累加进行条件过滤方式

通过字典映射效率很高,新测有效!

python DataFrame遍历

在数据分析的过程中,往往需要用到DataFrame的类型,因为这个类型就像EXCEL表格一样,便于我们个中连接、计算、统计等操作。在数据分析的过程中,避免不了的要对数据进行遍历,那么,DataFrame如何遍历呢?之前,小白每次使用时都是Google或百度,想想,还是总结一下~

小白经常用到的有三种方式,如下:

首先,先读入一个DataFrame

import pandas as pd
#读入数据
df = pd.read_table('d:/Users/chen_lib/Desktop/tmp.csv',sep=',', header='infer')
df.head()
 
-----------------result------------------
        mas  effectdate     num
0    371379    2019-07-15    361
1    344985    2019-07-13    77
2    425090    2019-07-01    105
3    344983    2019-02-19    339
4    432430    2019-02-21    162

1.DataFrame.iterrows()       

将DataFrame的每一行迭代为{索引,Series}对,对DataFrame的列,用row['cols']读取元素

for index, row in df.iterrows():
    print(index,row['mas'],row['num']) 
  
 
------------result---------------
0 371379 361
1 344985 77
2 425090 105
3 344983 339
4 432430 162

从结果可以看出,第一列就是对应的index,也就是索引,从0开始,第二第三列是自定义输出的列,这样就完成了对DataFrame的遍历。

2.DataFrame.itertuples()

将DataFrame的每一行迭代为元祖,可以通过row['cols']对元素进行访问,方法一效率高。

for row in df.itertuples():
    print(getattr(row, 'mas'), getattr(row, 'num')) # 输出每一行
 
 
-------------result-----------------
371379 361
344985 77
425090 105
344983 339
432430 162

从结果可以看出,这种方法是没有index的,直接输出每一行的结果。

3.DataFrame.iteritems()

这种方法和上面两种不同,这个是按列遍历,将DataFrame的每一列迭代为(列名, Series)对,可以通过row['cols']对元素进行访问。

for index, row in df.iteritems():
    print(index,row[0],row[1],row[2])
 
 
-------------result------------------
masterhotelid 371379 344985 425090
effectdate 2019-07-15 2019-07-13 2019-07-01
quantity 361 77 105

从结果可以看出,index输出的是列名,row是用来读取第几行的数据,结果是按列展示 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

来源:https://blog.csdn.net/mao15827639402/article/details/104053980

标签:python,pandas遍历每行,条件过滤
0
投稿

猜你喜欢

  • SQL中位数函数实例

    2024-01-25 17:21:55
  • git版本库介绍及本地创建的三种场景方式

    2023-07-11 11:22:18
  • MySQL数据库的23个特别注意事项

    2010-08-08 14:43:00
  • MySQL 百万级分页优化(Mysql千万级快速分页)

    2024-01-22 02:43:26
  • nodejs前端自动化构建环境的搭建

    2024-05-08 09:36:48
  • 基于PHP RSA密文过长加密解密 越过1024的解决方法

    2023-09-07 02:57:56
  • python的random和time模块详解

    2023-07-27 18:16:27
  • python政策网字体反爬实例(附完整代码)

    2021-04-27 19:51:32
  • CSS Sprites对CSS布局的意义、优点和缺点介绍

    2008-07-14 07:22:00
  • 从Oracle 表格行列转置说起第1/2页

    2009-09-24 12:51:00
  • PyTorch中torch.utils.data.DataLoader简单介绍与使用方法

    2023-10-30 07:12:00
  • Python字符串格式化输出代码实例

    2021-11-09 16:44:22
  • MySQL判别InnoDB表是独立表空间还是共享表空间的方法详解

    2024-01-18 14:23:34
  • asp我对后台安全的一些做法

    2011-09-01 19:22:09
  • pytorch 运行一段时间后出现GPU OOM的问题

    2021-05-21 17:01:34
  • 一个简单的ASP计数器代码

    2010-04-24 15:49:00
  • python反反爬虫技术限制连续请求时间处理

    2023-08-27 13:53:04
  • python3中pip3安装出错,找不到SSL的解决方式

    2022-02-15 23:33:17
  • python脚本和网页有何区别

    2023-04-01 21:24:10
  • python切片中内存的注意事项总结

    2022-12-23 00:04:09
  • asp之家 网络编程 m.aspxhome.com