使用 pandas 在多个列中应用 IF 条件
Applying an IF condition in multiple columns with pandas
我有一个 ascii 文件如下(示例)
id lon lat val1 val2 val3
1 22 38 67 66 87 89
2 23.5 39 56 10 90 98
3 22.5 38.5 34 45 56 78
对于特定点(纬度、经度),我想将变量 val1、val2、val3 设置为零。
例如对于 lon=22,lat=38 和 lon=23.5,lat=39
我尝试了以下操作(仅针对 val1 修改),但我得到了 ValueError: The truth value of a Series is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我该怎么做(也将所有变量 val 设置为 0)
import pandas as pd
col_names=['id','lon','lat','val1','val2','val3']
df = pd.read_csv(i,sep='\s+',names=col_names,header=None)
df.loc[df['Lon'] ==22 and df['Lat'] ==38, 'val1'] = 0
尝试添加括号。
df.loc[(df['Lon'] ==22) & (df['Lat'] ==38), 'val1'] = 0
而不是
df['Lon'] ==22 and df['Lat'] ==38
使用
(df['Lon'] ==22) & (df['Lat'] ==38)
如果你有多个以val
开头的列在一个步骤中处理,你可以使用.filter()
to filter the columns and set it into a list cols
. Then, use .loc
来设置选中的列,如下:
# put all columns that start with `val` into a list
cols = df.filter(regex='^val').columns
# set 0 all the variables val*
df.loc[(df['Lon'] == 22) & (df['Lat'] == 38), cols] = 0
我有一个 ascii 文件如下(示例)
id lon lat val1 val2 val3
1 22 38 67 66 87 89
2 23.5 39 56 10 90 98
3 22.5 38.5 34 45 56 78
对于特定点(纬度、经度),我想将变量 val1、val2、val3 设置为零。 例如对于 lon=22,lat=38 和 lon=23.5,lat=39
我尝试了以下操作(仅针对 val1 修改),但我得到了 ValueError: The truth value of a Series is ambiguous。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。 我该怎么做(也将所有变量 val 设置为 0)
import pandas as pd
col_names=['id','lon','lat','val1','val2','val3']
df = pd.read_csv(i,sep='\s+',names=col_names,header=None)
df.loc[df['Lon'] ==22 and df['Lat'] ==38, 'val1'] = 0
尝试添加括号。
df.loc[(df['Lon'] ==22) & (df['Lat'] ==38), 'val1'] = 0
而不是
df['Lon'] ==22 and df['Lat'] ==38
使用
(df['Lon'] ==22) & (df['Lat'] ==38)
如果你有多个以val
开头的列在一个步骤中处理,你可以使用.filter()
to filter the columns and set it into a list cols
. Then, use .loc
来设置选中的列,如下:
# put all columns that start with `val` into a list
cols = df.filter(regex='^val').columns
# set 0 all the variables val*
df.loc[(df['Lon'] == 22) & (df['Lat'] == 38), cols] = 0