计算值并创建新数据框

我有一个看起来像这样的数据框:


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

我想计算值 0<x<9、9<x<17 和 >=17 出现的次数。我试过这样做:


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

然而,所有这一切只是将值更改为标签。我想要的是一个新的数据框,它只有这样的值的计数:


df1

Green   Orange   Red

x   y   z

我缺少什么来完成这项任务?


慕村9548890
浏览 90回答 3
3回答

蓝山帝景

使用.groupbyand.transpose在此代码的末尾。df1 = pd.cut(df['Daily Risk Score'],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;bins=[0, 9, 17, np.inf],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;labels=['Green','Orange','Red']).reset_index(). \&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;groupby('Daily Risk Score').count().transpose()df1输出:&nbsp;Daily Risk Score&nbsp; &nbsp;Green&nbsp; &nbsp;Orange&nbsp; Red&nbsp;index&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp; &nbsp;4&nbsp; &nbsp; &nbsp; &nbsp;2

慕仙森

尝试:df1=df.groupby(pd.cut(df['Daily Risk Score'], bins=[0, 9, 17, np.inf], labels=['Green','Orange','Red'])).size()df1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Daily Risk ScoreGreen&nbsp; &nbsp; &nbsp;3Orange&nbsp; &nbsp; 5Red&nbsp; &nbsp; &nbsp; &nbsp;2dtype: int64或者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:&nbsp; &nbsp; Green&nbsp; &nbsp;Orange&nbsp; Red1&nbsp; &nbsp;3&nbsp; &nbsp; &nbsp; &nbsp;5&nbsp; &nbsp; &nbsp; &nbsp;2

慕丝7291255

我尝试了一些不同的方法。这也很容易。尝试一下,如果您遇到任何问题/错误,请告诉我。干得好:df["col"] = 0for i in range(len(df)):&nbsp; &nbsp; if 0<df["Daily Risk Score"][i]<9:&nbsp; &nbsp; &nbsp; &nbsp; df["col"][i] = "0<Daily Risk Score<9"&nbsp; &nbsp; elif 9<df["Daily Risk Score"][i]<17:&nbsp; &nbsp; &nbsp; &nbsp; df["col"][i] = "9<Daily Risk Score<17"&nbsp; &nbsp; elif 9<df["Daily Risk Score"][i]<17:&nbsp; &nbsp; &nbsp; &nbsp; df["col"][i] = "Daily Risk Score>=17"&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; df["col"][i] = "other"df["col"].value_counts()df.drop(columns=["col"])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python