0

I have a dataframe that looks like this:

df
    Daily Risk Score
0   13.0
1   10.0
2   25.0
3   7.0
4   18.0
... ...
672 14.0
673 9.0
674 15.0
675 6.0
676 13.0

I want to count the number of times a value of 0<x<9, 9<x<17 and >=17 occurs. I tried doing this:

df1=pd.cut(df['Daily Risk Score'], bins=[0, 9, 17, np.inf], labels=['Green','Orange','Red'])

However, all this does is change the value to the label. What I want is a new dataframe that just has the counts of the values like this:

df1
Green   Orange   Red
x   y   z

What am I missing to accomplish this task?

3 Answers 3

1

Use .groupby and .transpose at the end of this code.

df1 = pd.cut(df['Daily Risk Score'],
             bins=[0, 9, 17, np.inf],
             labels=['Green','Orange','Red']).reset_index(). \
             groupby('Daily Risk Score').count().transpose()
df1

output:

 Daily Risk Score   Green   Orange  Red
 index              3       4       2
Sign up to request clarification or add additional context in comments.

Comments

0

I tried it with a bit different method. Its easy too. Try it out and let me know if you face any issue/error. Here you go:

df["col"] = 0
for i in range(len(df)):
    if 0<df["Daily Risk Score"][i]<9:
        df["col"][i] = "0<Daily Risk Score<9"
    elif 9<df["Daily Risk Score"][i]<17:
        df["col"][i] = "9<Daily Risk Score<17"
    elif 9<df["Daily Risk Score"][i]<17:
        df["col"][i] = "Daily Risk Score>=17"
    else:
        df["col"][i] = "other"
df["col"].value_counts()
df.drop(columns=["col"])

Comments

0

Try:

df1=df.groupby(pd.cut(df['Daily Risk Score'], bins=[0, 9, 17, np.inf], labels=['Green','Orange','Red'])).size()

df1:

          Daily Risk Score
Green     3
Orange    5
Red       2
dtype: int64

OR

df1=df.groupby(pd.cut(df['Daily Risk Score'], bins=[0, 9, 17, np.inf], labels=['Green','Orange','Red'])).size()
df2 = pd.DataFrame(df1.reset_index().values.T)
df2.columns = df2.iloc[0]
df2 = df2[1:]

df2:

    Green   Orange  Red
1   3       5       2

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.