How to add columns with "a" in the field name
Question:
This above is a simple example
I want to add the data which columns with "a"
df['a+abc+bca'] = df[['a', 'abc','bca']].sum(axis=1)
Although this method can be counted successfully, it is not very flexible, because if I have many columns whose field names contain "A", the drawbacks of this method will appear.
I would like to know if there is a more convenient or flexible way to achieve this? I am a novice in Python, if this seems to be a very simple question, please be able to answer it for me, thank you very much for your help.
Answers:
Use DataFrame.filter(like=)
cols = df.filter(like='a').columns
df['+'.join(cols)] = df[cols].sum(axis=1)
print(df)
a b abc bca a+abc+bca
0 1 2 3 4 8
The filter solution is easier but this works too.
a_columns = [column for column in columns if ‘a’ in column]
df[‘all_a_sum’] = df[a_columns].sum(axis=1)
This above is a simple example
I want to add the data which columns with "a"
df['a+abc+bca'] = df[['a', 'abc','bca']].sum(axis=1)
Although this method can be counted successfully, it is not very flexible, because if I have many columns whose field names contain "A", the drawbacks of this method will appear.
I would like to know if there is a more convenient or flexible way to achieve this? I am a novice in Python, if this seems to be a very simple question, please be able to answer it for me, thank you very much for your help.
Use DataFrame.filter(like=)
cols = df.filter(like='a').columns
df['+'.join(cols)] = df[cols].sum(axis=1)
print(df)
a b abc bca a+abc+bca
0 1 2 3 4 8
The filter solution is easier but this works too.
a_columns = [column for column in columns if ‘a’ in column]
df[‘all_a_sum’] = df[a_columns].sum(axis=1)