[英]Loop pandas column and replace values
我已經閱讀了很多帖子,但沒有成功。 我有一個我希望的列“百分比”,但在類別 1、2、3、4 中。 dataframe 被稱為“數據”。 我試過了
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.