【问题标题】:Count of value occurrence in two columns stimulatenously, python刺激两列中出现的值计数,python
【发布时间】:2018-08-24 21:14:21
【问题描述】:

早安,

我有一个问题,一个非常基本的问题。假设我有一个数据集,其中用户对电影的评分在行中,电影在列中。我需要找到与 movie2 一起出现的电影。例如,对于电影 1,同时对电影 1 进行评分的电影 2 评分者的百分比为 0.5 - 观看电影 1 和电影 2 的人数为 1 除以观看和评分电影 2 的总人数。

数据集:

import numpy as np
df = np.array([['','Movie1','Movie2','Movie3'],
                ['User1',1,0,2],
                ['User2',2,4,4],
                ['User3',4,0,4],
                ['User4',0,2,4]])
print(pd.DataFrame(data=df[1:,1:],
                  index=df[1:,0],
                  columns=df[0,1:]))

下面的行查找对电影评分的用户数量。我的问题是如何再添加一个条件,该条件还检查 col movie2 中的相应单元格是否不是 0 - 0 表示一个人没有看过电影,它在原始数据集中被标记为缺失值:

df.apply(lambda x: x[x!=0]).count(axis=0)

【问题讨论】:

  • 我不太明白.. 你能详细说明一下吗? For example, for the movie1, the percentage of the movie2 raters who also rated the movie1 is 0.5。如何? the number of people who saw both, the movie1 and movie2 is 1 divided by the total number of people seeing and rating the movie2.?这是什么逻辑?
  • 查看下面的回复。

标签: python pandas


【解决方案1】:

代码中有两件事

首先你通过np.array创建数据框,基于官方文档np.array,每次只接受一种数据类型,所以你的numeric会自动转换为string

df.applymap(type)
Out[787]: 
              Movie1         Movie2         Movie3
User1  <class 'str'>  <class 'str'>  <class 'str'>
User2  <class 'str'>  <class 'str'>  <class 'str'>
User3  <class 'str'>  <class 'str'>  <class 'str'>
User4  <class 'str'>  <class 'str'>  <class 'str'>

第二个解决方案

maskdf=df.ne('0')

maskdf.Movie1[maskdf.Movie2].mean()
Out[795]: 0.5

更改您的 apply 代码

df.ne('0').sum(axis=1)
Out[786]: 
User1    2
User2    3
User3    2
User4    2
dtype: int64


df.ne('0').sum()
Out[788]: 
Movie1    3
Movie2    2
Movie3    4
dtype: int64

【讨论】:

  • 嗨 Wen 和 Abhishek,感谢您的回复。我需要计算有多少用户评论(评分!= 0),例如,电影 1 和电影 2,然后除以评论电影 2 的用户数。电影 3 也是如此,即有多少用户评论了电影 3 和电影 2,然后除以评论电影 2 的用户数。所以,我逐个列(提醒你,电影在列中)检查有多少用户评论了相应的电影和电影2。这是正常逻辑,@Abhishek)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多