Hi - in Pandas dataframes I have the following dataframe and list of variables: import…
- User
Hi - in Pandas dataframes I have the following dataframe and list of variables:
import pandas as pd
df1 = pd.DataFrame(data={ “col1”: [“ab#(ab)_1_12_hello”, “ab#(ab)_1_12_hello”, “cde(2012/06/03)_1_12_hello”, “ab#(ab)_1_12_hello”, ], “col2”: [“cde(2012/06/03)_2_12_hello”, “cde(2012/06/03)_1_24_hello”, nan, “efg_3_24_hello”, ], “col3”: [“efg_3_12_hello”, “efg_3_12_hello”, nan, nan, ] })
var_names = [“ab#(ab)”, “cde(2012/06/03)”, “efg”]
I would like to count the number of times in each row of df1 that each one of the variables in var_names is present as a substring. Pls use escape characters in the search. I also only want to count the variable once for each row where it is present. Finally, please also take into account that I have some nan numbers.
- Assistant
You can use the
str.count()method to count the number of occurrences of each variable in the rows of the dataframe. Here's how you can do it:import pandas as pd import numpy as np df1 = pd.DataFrame(data={ "col1": ["ab#(ab)_1_12_hello", "ab#(ab)_1_12_hello", "cde(2012/06/03)_1_12_hello", "ab#(ab)_1_12_hello"], "col2": ["cde(2012/06/03)_2_12_hello", "cde(2012/06/03)_1_24_hello", np.nan, "efg_3_24_hello"], "col3": ["efg_3_12_hello", "efg_3_12_hello", np.nan, np.nan] }) var_names = ["ab#(ab)", "cde(2012/06/03)", "efg"] # Replace nan with an empty string df1 = df1.replace(np.nan, '', regex=True) # Count occurrences of each variable in each row for var in var_names: df1[var] = df1.apply(lambda row: row.str.count(var).sum(), axis=1) # Print the resulting dataframe print(df1)