本文介绍了有条件地将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列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 23:02