[英]Change pandas dataframe column values based on other columns in dataframe
[英]How to change values of a pandas dataframe column filtered by values of other columns
如何在Python中编写以下R代码?
df = data.frame( a=c("apple", "banana", "orange", "apple"),
b=c(NA, 3, NA, 5)
c=c(2, 1, 0, NA)
d=c(1, NA, NA, 3) )
df[ df$a =="apple" & !is.na(df$b), "c"] = df[ df$a =="apple" & !is.na(df$b), "d"]
我在下面尝试过并收到TypeError:“系列”对象是可变的,因此无法将它们散列为错误
# Python code that receives an error
# df is Pandas DataFrame
df.loc[ (df.a=="apple") & ~df.b.isnull(), 'c'] = df.loc[ (df.a=="apple") & ~df.b.isnull(), 'd']
df['c'] = df.apply( lambda row: row['d'] if row['a']=="apple" & ~np.isnan(row['b']) else row['c'])
预期结果是df ['c']将具有[2,1,0,3]
在熊猫
df.loc[ (df.a =="apple") & (df.b.notnull()), "c"]=df.d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.