I'm trying to copy data from a set of columns to a different column in the same DataFrame. But prior to that I wanted to search if those columns exist in the DataFrame and add those which are present and ignore the rest. I did,
col_list1 = ['Column1','Column2','Column3']
test1 = any([ i in df.columns for i in col_list1 ])
if test1==True:
df['CH']=df['Column1'] df['Column2'] df['Column3']
this code is throwing me a keyerror . I want it to ignore columns that are not present and add only those that are present
CodePudding user response:
Instead of just concatenating the columns with
, collect them into a list and use sum
with axis=1
:
df['CH'] = np.sum([df[c] for c in cl if c in df], axis=1)
CodePudding user response:
IIUC, you can use Python set
or Series.isin
to find the common columns
cols = list(set(col_list1) & set(df.columns))
# or
cols = df.columns[df.columns.isin(col_list1)]
df['CH'] = df[cols].sum(axis=1)