Python 有条件地将1或0设置为新列
一个非常简单的问题: 如果我有这样一个数据帧:Python 有条件地将1或0设置为新列,python,pandas,Python,Pandas,一个非常简单的问题: 如果我有这样一个数据帧: hour 0 0 1 1 2 1 3 2 4 2 ... 我想创建一个新的列“午餐”,如果可以的话,它的值为1 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 Fal
hour
0 0
1 1
2 1
3 2
4 2
...
我想创建一个新的列“午餐”,如果可以的话,它的值为1
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
In[231]:df['午餐]=(df['hour']试试:
>>df['午餐]=df['hour']。应用(如果x>=11或x>>df,则λx:1
小时午餐
0 0 1
1 1 1
2 1 1
3 2 0
4 2 0
您可以使用矢量化方法(这里的减号运算符用于对布尔掩码求反):
11@ana是什么意思?猜测一下,hour
是12小时内的读数,所以它应该是完整的。但是如果不能检查上午/下午或日期,那么它总是正确的。
>>> df['lunch']=df['hour'].apply(lambda x: 1 if x >= 11 or x <= 1 else 0)
>>> df
hour lunch
0 0 1
1 1 1
2 1 1
3 2 0
4 2 0
df['lunch'] = (-df.hour.isin(range(2,11))).astype(int)
Out[368]:
hour lunch
0 0 1
1 1 1
2 1 1
3 2 0
4 2 0