猿问

如果条件匹配,如何添加值,python

我想在每行中为“Score”列添加“1”,其中以下语句为真,


import pandas as pd

import numpy as np



df = pd.read_csv(Path1 + 'Test.csv')

df.replace(np.nan, 0, inplace=True)

df[(df.Day7 >= 500)]

样本

输出

http://img.mukewang.com/61b0679f0001b1b701920140.jpg

慕村225694
浏览 202回答 3
3回答

暮色呼如

你可以试试下面的。df['score']=np.where(df['Day7']>=500,1,"")或者根据 OP 的评论(在此处添加@anky_91 的增强解决方案):np.where((df['Day7']>=500)&(df['Day7']<1000),1,"")当我们打印以下值时df将是输出。&nbsp; &nbsp; Cat&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Day7&nbsp; &nbsp; score0&nbsp; &nbsp;Advertisir&nbsp; &nbsp;145&nbsp; &nbsp;&nbsp;1&nbsp; &nbsp;Blogs&nbsp; &nbsp; &nbsp; &nbsp; 56&nbsp;2&nbsp; &nbsp;Business&nbsp; &nbsp; &nbsp;92&nbsp;3&nbsp; &nbsp;Classfied&nbsp; &nbsp; 23&nbsp;4&nbsp; &nbsp;Continuin&nbsp; &nbsp; 110&nbsp; &nbsp;&nbsp;5&nbsp; &nbsp;Corporate&nbsp; &nbsp; 1974&nbsp; &nbsp; &nbsp;1

四季花海

你已经成功了一半。只需使用df.loc[mask, "Score"] = 1:import numpy as npimport pandas as pddf = pd.DataFrame({"Day7":np.random.rand(5)*1000,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Score": np.random.rand(5)})print(df)df.loc[(df.Day7>=500), "Score"] = 1print(df)

沧海一幻觉

df&nbsp;=&nbsp;df.assign(Score=0) df.Score&nbsp;=&nbsp;df.Day7&nbsp;>=&nbsp;500
随时随地看视频慕课网APP

相关分类

Python
我要回答