简体   繁体   English

熊猫根据另一列的非空值创建一个新列

[英]Pandas create a new column based on non-null value of another column

I have a dataframe where I want to create a new column based on an existing column where the values are non null. 我有一个数据框,我想根据值不为null的现有列创建一个新列。

The existing column is in decimals and some rows are null. 现有列为小数,某些行为null。 I want to create a new column in integers. 我想用整数创建一个新列。

I am using lambda but keep getting a syntax error. 我正在使用lambda,但一直收到语法错误。 Could anyone tell me what's wrong? 谁能告诉我怎么了? Thanks 谢谢

df['new'] =  df['old'].apply(lambda x: int(x) if x>=0)

I also tried: 我也尝试过:

df['new'] =  df['old'].apply(lambda x: int(x) if x.isnull == False)

and this one: 还有这个:

df['new'] =  df['old'].apply(lambda x: x.astype(int) if x>=0)

The syntax error is pointing to the last close parenthesis. 语法错误指向最后一个右括号。

df['new'] =  df['old'].apply(lambda x: int(x) if x>=0)

您需要在三元运算符的末尾添加一个else

df['new'] =  df['old'].apply(lambda x: int(x) if x>=0 else 'Nope')

You got syntax error, because your lambda function is not correct. 您收到语法错误,因为您的lambda函数不正确。 Specifically, the if ... else ... conditional expression is wrong. 具体来说, if ... else ... 条件表达式是错误的。 The conditional expression must be 条件表达式必须为

conditional_expression ::=  or_test [“if” or_test “else” expression]

You were missing else part. 您缺少else部分。

Another thing I would like to mention is that the graceful way to convert the data type is to use astype function . 我想提到的另一件事是,转换数据类型的一种优美方法是使用astype函数 If you want to cast data on some condition, you could do like: 如果要在某种条件下投射数据,可以执行以下操作:

new = df.loc[df.old>0].astype('int')

Then new would become a Series you need. 然后new将成为您需要的系列。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM