I have a dataframe like this:
import pandas as pd
import numpy as np
df = pd.DataFrame({"a":[10, 13, 15, 30],
"b:1":[np.nan, np.nan, 13, 14],
"b:2":[6, 7, np.nan, np.nan]})
I would like to combine columns when they start with "b:" into one column "b". I could simply use df["b"] = df["b:1"].combine_first(df["b:2"]) in this case, but this is an example of a larger dataframe and sometimes it can has also something like "b:3" and forward, or even other columns with "c:1, c:2" and these last ones I wouldn’t like to merge.
Anyone could show me how I could do that so my final dataframe would be:
df
Out[23]:
a b:1 b:2 b
0 10 NaN 6.0 6.0
1 13 NaN 7.0 7.0
2 15 13.0 NaN 13.0
3 30 14.0 NaN 14.0
>Solution :
You can use str.contains for df.columns and then sum on axis=1:
col_b = df.columns[df.columns.str.contains('b')]
df['b'] = df[col_b].sum(axis=1)