-2

This is my data set:

    q1  q2  q3     q4
0   a   a   a   a
1   b   a   a   a
2   c   c   b   a
3   d   d   b   a
4   a   a   a   a
5   b   c   b   a
6   b   a   b   a
7   c   c   b   a
8   d   d   b   a

where column

  • q1 has 'a','b','c','d' column values.
  • q2 has 'a','c','d' column values.
  • q3 has 'a','b' column values.
  • q4 has 'a' column values.

I want to run a for-loop for all columns with the common equation, but all the columns do not have all values. I am getting an error.

Example: enter image description here

col = ['q1', 'q2', 'q3', 'q4']

for i in col:
    print((df[i].value_counts()['a']) + (df[i].value_counts()['b']) + (df[i].value_counts()['c']) + (df[i].value_counts()['d']))
1
  • can you add the expected output? Commented Feb 17, 2023 at 9:26

3 Answers 3

1

You can try with multiple if conditions to check the value in the particular column:

col = ['q1', 'q2', 'q3', 'q4']

for i in col:
    count = 0
    if 'a' in df[i].unique():
        count += df[i].value_counts()['a']
    if 'b' in df[i].unique():
        count += df[i].value_counts()['b']
    if 'c' in df[i].unique():
        count += df[i].value_counts()['c']
    if 'd' in df[i].unique():
        count += df[i].value_counts()['d']
    print(count)
Sign up to request clarification or add additional context in comments.

Comments

0

You can try by declaring the values in your for():

col = ['q1', 'q2', 'q3', 'q4']
values = ['a', 'b', 'c', 'd']
for i in col:
    count = 0
    for v in values:
        if v in df[i].values:
            count += df[i].value_counts()[v]
    print(count)

Comments

0

you can use, create list and append:

list_C = []
for i in cols:
    a = df[i].str.count("A").sum()
    list_C.append(a)
    b = df[i].str.count("B").sum()
    list_C.append(b)
    c = df[i].str.count("C").sum()
    list_C.append(c)
    d = df[i].str.count("D").sum()
    list_C.append(d)

print(list_C)
print(sum(list_C))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.