python - 在 pandas 中创建一个分数列,其值取决于另一列的百分位数

标签 python python-3.x pandas

我有以下数据框:

User_ID Game_ID votes
1         11    1040
1         11    nan
1         22    1101
1         11    540
1         33    nan
2         33    nan
2         33    290
2         33    nan

根据 votes 列中值的百分位数,需要按照以下规则创建一个新列:

If the “votes” value is >= 75th percentile assign a score of 2

If >=25th percentile assign a score of 1

If <25th percentile assign a score of 0.

最佳答案

您可以通过调用 describe 和使用列表理解来获取百分位数:

percentiles = df.votes.describe()
df['scores'] = [2 if x >= percentiles['75%'] else (0 if x < percentiles['25%'] else 1) for x in df.votes]

关于python - 在 pandas 中创建一个分数列,其值取决于另一列的百分位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55741046/

相关文章:

python - NumPy 数组索引

javascript - 如何 "Lock down"V8?

python - 在 Python 3 中捕获特定的 OSError 异常

python - 在 Python 中有条件地基于分组创建一个新列

python - 如何从 BaseHTTPRequestHandler python 获取 x509.Certificate

python - 将多个日期时间数据帧行分组为单个行

python - Pandas 变频

python - Pandas :检查是否存在具有某些值的行

python-3.x - PyQt4 和 Python 3.5 的问题

python - 通过将方法名称保存在 python 的 for 循环中的 var 中来连接到类方法