'Survey - DF1 - Questions are in Row1, In DF2 all questions are listed in the first column Python
Please if you can help me with this,
I want to calculate Number of Yes from DF1 to Df2
Something like this
for x in DF2['Questions']:
if x == first row of DF1 count 'Yes'
and it goes through the whole row and where the condition is met, it counts yes and posts in a Dataframe2['Yes']
I have been trying to do this but none of what i did work. Please if you can help me or suggest what should i look at.
Thank you
Solution 1:[1]
df_ = df[['Q1', 'Q2']].eq('Yes').sum(axis=0).to_frame(name='Yes').rename_axis('Questions').reset_index()
print(df_)
Questions Yes
0 Q1 1
1 Q2 0
To illustrate step by step:
First you can use df[['Q1', 'Q2']].eq('Yes') to get a boolean dataframe which tells if the value is Yes
Q1 Q2
0 True False
1 False False
Then you can sum this boolean dataframe by row with .sum(axis=0)
Q1 1
Q2 0
dtype: int64
At last, you can reset the Series to dataframe with .to_frame(name='Yes'), rename the index with .rename_axis('Questions') and reset it back to column with .reset_index()
Questions Yes
0 Q1 1
1 Q2 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ynjxsjmh |


