Skip to main content
 首页 » 编程设计

python之使用 if/else 语句创建一个新的可变数值列

2025年05月04日16shihaiming

我有一个包含“y”列的数据集,其中存在特定值。我想使用该列并创建一个新列 (z),表示如果 y 值为 47472,则 z 应为 1000,如果 y <1000,则 z=y*2,否则所有其他值应为 2000。 这是数据的模拟示例。我没有“z”列,但我想创建它:

          y      z 
0      1751   2000 
1       800   1600 
2     10000   2000 
3       350    700 
4       750   1500 
5      1750   3500 
6     30000   2000 
7     47472   1000 
 
 
def test(y): 
    if y == 47472: 
        z=1000 
    elif y < 1000: 
        z=y*2 
    else: 
        z=2000 
    return Z 
 
# I tried to call the above function below 
z = test(y) 
z 

但我没有得到结果,而是显示以下错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

请您参考如下方法:

问题是你在 if 语句中使用了一个系列,例如:

if y == 47472: 

假设 y 是您的 DataFrame 的一部分,这将产生一个 bool 值列表:

>>> df['y']==47472 
0    False 
1    False 
2    False 
3    False 
4    False 
5    False 
6    False 
7     True 
Name: y, dtype: bool 

这是不合法的,因此建议您使用返回一个 bool 值的 bool 函数,例如 any()、all() 等。 相反,您应该使用 boolean indexing :

# df is the dataframe with your data 
# adding column z 
df['z'] = pd.Series(np.zeros(df.shape[0])) 
# if y == 47472 then put 1000 
df.loc[df['y']==47472, 'z'] = 1000 
# filter <1000 
df.loc[df['y']<1000, 'z'] = 2*df['y'] 
# now set rest to 2000 (i.e. ones that do not comply previous 2 conditions) 
df.loc[(df['y']>=1000) & (df['y']!=47472),'z'] = 2000 

编辑:正如 EdChum 评论的那样,我正在表演 chained indexing :

df['z'][df['y']<1000] = 2*df['y'] 

应该使用 loc 来避免:

df.loc[df['y']<1000, 'z'] = 2*df['y']