python - 循环熊猫列并替换值
问题描述
我已经阅读了很多帖子,但没有成功。我有一个我希望的列“百分比”,但在类别 1、2、3、4 中。数据框称为 'data' 。我试过了
for i in data.index:
if i > 0.7:
df.at[i,"percent"] =1
if i <0.7 and i>0:
df.at[i, "percent"] = 2
if i <0 and i > -0.4:
df.at[i, "percent"] = 3
if i < 0.4:
df.at[i, "percent"] = 4
但看起来一切都被替换为1。我做错了什么?
解决方案
import pandas as pd
import numpy as np
df = pd.DataFrame([[0.4,"x"],[0.5,"x"], [0.6,"y"], [0.7,"z"], [0.8,"z"]], columns=["pc","val"])
df['pc_quant'] = np.digitize(df['pc'], [.4, .7])
print(df)
给你:
pc val pc_quant
0 0.4 x 1
1 0.5 x 1
2 0.6 y 1
3 0.7 z 2
4 0.8 z 2
推荐阅读
- r - R根据变量重新调整第二个Y轴
- python - Flask 会话不会跨请求持续存在
- javascript - react-native run-android 失败
- python - 如何在数据框中添加缺失的日期并填充python中的其他相应列?
- django - Stripe 使用 django 的 webhook 说:stripe.error.SignatureVerificationError
- css - 仅在 Chrome 中出现奇怪的 CSS 阴影错误?
- android - 由于带有新代码的新版本,有关如何在 Android Studio 中编写 Soundboard 的教程后出现问题
- amazon-s3 - 有没有办法在 S3 存储桶策略中包含组织 ID
- lua - LuaJIT 的 C 解析器中的字符串文字支持
- apache-kafka - KAFKA - 错误锁定目录时磁盘错误