Reputation: 461
i have this df
data={"col1":["n",3,"n",5,"n",2,6],
"col2":[4,"n",4,6,"n","n",5],
"col3":[7,"n",0,"n","n",6,7],
"col4":[14,11,22,8,6,"n",9],
"col5":[0,5,"n",3,8,"n",9],
"type":["B","n","n","n","B","A","B"],
"number":["one","n","n","n","one","two","n"]}
df=pd.DataFrame.from_dict(data)
print(df)
i like to have new column that sum all "n" in evry row/ Something like this maybe:
df["sum_n"]=df[["list of all col"]].sum("n",axis=)
its need to look like this
data={"col1":["n",3,"n",5,"n",2,6],
"col2":[4,"n",4,6,"n","n",5],
"col3":[7,"n",0,"n","n",6,7],
"col4":[14,11,22,8,6,"n",9],
"col5":[0,5,"n",3,8,"n",9],
"type":["B","n","n","n","B","A","B"],
"number":["one","n","n","n","one","two","n"],
"sum_n":[1,4,4,3,3,3,1]}
df=pd.DataFrame.from_dict(data)
df
Upvotes: 0
Views: 245
Reputation: 61910
Do:
df['sum_n'] = df.eq('n').sum(1)
print(df)
Output
col1 col2 col3 col4 col5 type number sum_n
0 n 4 7 14 0 B one 1
1 3 n n 11 5 n n 4
2 n 4 0 22 n n n 4
3 5 6 n 8 3 n n 3
4 n n n 6 8 B one 3
5 2 n 6 n n A two 3
6 6 5 7 9 9 B n 1
Upvotes: 3