Skip to main content
 首页 » 编程设计

python之Pandas:如何识别数据框列中的值并进行一些数学运算

2024年10月01日7落叶无声

我想做一些操作,这样我就可以产生这样的东西:

换句话说,如果 Name 中的值在“first_list”中,我想将“Values”乘以二。如果它们在“second_list”中,我想将它们乘以 0.5。如果他们都不在其中(对于 Nick 和 Nicky),则不要做任何事情。

这是我的:

first_list = ['John', 'James', 'Julius', 'Alex'] 
second_list = ['Lilly', 'Alexis', 'Becly'] 
if df['Name'].isin(first_list).any(): 
    df['New Values'] = df['Values'] * 2 
elif df['Name'].isin(second_list).any(): 
    df['New Values'] = df['Values'] * 0.5 

但它并没有按照我的意愿进行乘法运算。相反,它给了我:

请您参考如下方法:

让我们使用 np.where 和 isin:

df['New Value'] = (np.where(df.Name.isin(first_list), 
                            df.Values*2, 
                            np.where(df.Name.isin(second_list), 
                                     df.Values*.5, 
                                     df.Values))) 

设置:

df = pd.DataFrame({'Name':['John','Lily','Alexis','Becky','James','Julian','Alex','Nick','Nicky'],'Values':[50,100,30,60,40,20,80,25,46]}) 
 
first_list = ['John','James','Julius','Alex'] 
second_list = ['Lily','Alexis','Becky'] 

输出:

     Name  Values  New Value 
0    John      50      100.0 
1    Lily     100       50.0 
2  Alexis      30       15.0 
3   Becky      60       30.0 
4   James      40       80.0 
5  Julian      20       20.0 
6    Alex      80      160.0 
7    Nick      25       25.0 
8   Nicky      46       46.0