从其他列派生 DataFrame 列而不编写任何循环

我有一个包含两列(动词和出现)的 DataFrame。我能够创建一个新列来确定动词的字符数(即长度):

df['length'] = df['verb'].str.len()

第二个要求是创建一个包含文本的新列。如果ocurrence等于 1,则写'Unique'; 如果ocurrence小于或等于5,则写'Medium';否则'High'……

...这是我迄今为止编写的代码...

df['class'] = 'Unique' if df['ocurrence'] == 1 else 'Medium' if df['ocurrence'] <= 5 else 'High'

......但它不起作用。


慕侠2389804
浏览 146回答 2
2回答

狐的传说

使用pd.cut:df['class'] = pd.cut(df.occurrence, bins=[0,1,5,np.inf], labels=['Unique','Medium','High'])例如:df = pd.DataFrame({'occurrence':np.random.randint(0,10,10)})>>> df&nbsp; &nbsp;occurrence0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;51&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;12&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;63&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;74&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;55&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;76&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;77&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;18&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;29&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;7df['class'] = pd.cut(df.occurrence, bins=[0,1,5,np.inf], labels=['Unique','Medium','High'])>>> df&nbsp; &nbsp;occurrence&nbsp; &nbsp;class0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;5&nbsp; Medium1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1&nbsp; Unique2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;6&nbsp; &nbsp; High3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; High4&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;5&nbsp; Medium5&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; High6&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; High7&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1&nbsp; Unique8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2&nbsp; Medium9&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;7&nbsp; &nbsp; High
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python