[英]Create a new column using a condition from other two columns in a dataframe
I'm trying to create a column as I detailed in the next lines of code where if there is a zero value in one of the rows of the dataframe create a 'Sin Valor' value in the row of the new column of this dataframe.我正在尝试创建一个列,正如我在下一行代码中详述的那样,如果 dataframe 的其中一行中有一个零值,则在此 dataframe 的新列的行中创建一个“Sin Valor”值。
import pandas as pd
data = pd.DataFrame({
'Qu1' : [12,34,0,45,0],
'Qu2' : ['A1','A2',"B0",'C2','B0'],
'Control' : ['A1', 'A2','Sin Valor/ -' + "B0" ,'C2','Sin Valor/ -'+ "B0"]})
In Excel, what I am trying to do should be something like this picture attached.在 Excel 中,我想做的应该是附上这张图片。
I was trying to create a function to do that and applying via lambda function but this isn´t working.我试图创建一个 function 来做到这一点并通过 lambda function 应用,但这不起作用。
def fill_df(x):
if data["Qu1"] == 0:
return x.zfill('Sin Valor/ -')
else:
return ' '
data['Control'] = data.apply(fill_df)
Is it possible to do that?有可能这样做吗? Every help is welcome.
欢迎任何帮助。 Thanks.
谢谢。
use np.where to accomplish it使用 np.where 来完成它
df['ctrl'] = np.where(df['Qu1'] == 0,
'Sin Valor/-'+df['Qu2'],
df['Qu2'])
df
I introduced 'ctrl' column, that meets your requirement and matches 'control' (desired) column我介绍了“ctrl”列,它符合您的要求并匹配“控制”(所需)列
Qu1 Qu2 Control ctrl
0 12 A1 A1 A1
1 34 A2 A2 A2
2 0 B0 Sin Valor/ -B0 Sin Valor/-B0
3 45 C2 C2 C2
4 0 B0 Sin Valor/ -B0 Sin Valor/-B0
mask = df['Qu1'] == 0
df.loc[mask, 'Control'] = 'Sin Valor/ -' + df['Qu2'][mask]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.