我有一个包含两列(动词和出现次数)的 DataFrame。我能够创建一个新列来确定动词的字符数(即长度):
df['length'] = df['verb'].str.len()
第二个要求是创建一个包含文本的新列。如果ocurrence
等于1,则写入'Unique'
;如果ocurrence
小于或等于5,则写入'Medium'
;否则“高”
...
...这是我到目前为止编写的代码...
df['class'] = 'Unique' if df['ocurrence'] == 1 else 'Medium' if df['ocurrence'] <= 5 else 'High'
...但它不起作用。
最佳答案
使用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
occurrence
0 5
1 1
2 6
3 7
4 5
5 7
6 7
7 1
8 2
9 7
df['class'] = pd.cut(df.occurrence, bins=[0,1,5,np.inf], labels=['Unique','Medium','High'])
>>> df
occurrence class
0 5 Medium
1 1 Unique
2 6 High
3 7 High
4 5 Medium
5 7 High
6 7 High
7 1 Unique
8 2 Medium
9 7 High
关于python - 从其他列派生 DataFrame 列,无需编写任何循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53421775/