python - 从其他列派生 DataFrame 列,无需编写任何循环

标签 python pandas

我有一个包含两列(动词和出现次数)的 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/

相关文章:

python - matplotlib 动画保存不遵守 blit=True 但它似乎在 plt.show() 中工作得很好

Python pandas 数据框添加前一行值

python - 获取 Pandas 系列的日期

python - 将 DF 拆分为多个 DF 并对每个 DF 执行所有操作的函数

python - Pandas GroupBy,将新的数字列表列与另一列数字列表进行比较

python - 使用 Tkinter 的动画 gif 没有透明度

python - tensorflow 未找到错误

python - TensorFlow 估计器类数不变

python-3.x - Pandas Groupby 的分类特征需要太多的 RAM 和时间

python Pandas : Getting the locations of a value in dataframe