有条件地将1或0设置为新的Pandas列

编程入门 行业动态 更新时间:2024-10-24 18:18:08
本文介绍了有条件地将1或0设置为新的Pandas列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一个非常简单的熊猫问题:

A pretty straightforward pandas question:

如果我有这样的数据框:

If I have a dataframe as such:

hour 0 0 1 1 2 1 3 2 4 2 ...

我想创建一个新的午餐"列,如果11< = hour< = 1则值为1,否则为0,那么什么是最好的且计算最快的方法呢?

and I'd like to create a new column 'lunch' that'll have the value 1 if 11<=hour<=1 and 0 otherwise, what's the best and computationally quickest way to do this?

推荐答案

您可以

In [231]: df['lunch'] = (df['hour']<=11) & (df['hour']<=1) In [232]: df['lunch'] Out[232]: 0 True 1 True 2 True 3 False 4 False Name: lunch, dtype: bool In [233]: df['lunch'].astype(int) Out[233]: 0 1 1 1 2 1 3 0 4 0 Name: lunch, dtype: int32

更多推荐

有条件地将1或0设置为新的Pandas列

本文发布于:2023-10-24 08:47:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1523483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   有条件   Pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!