脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - python pandas遍历每行并累加进行条件过滤方式

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

2022-12-29 12:04向日葵 Python

这篇文章主要介绍了python pandas遍历每行并累加进行条件过滤方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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

延伸 · 阅读

精彩推荐