Rau*_*aul 8 python dataframe pandas
我有一个带有DATE行的数据帧,如果日期是周末日,我需要将其转换为值为1的行,如果不是,则需要将其转换为0.
到目前为止,我将数据转换为工作日
df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek
Run Code Online (Sandbox Code Playgroud)
有没有办法在没有功能的情况下创建这个"WEEKEND"行?
谢谢!
dag*_*rha 15
这是我提出的解决方案:
df['WEEKDAY'] = ((pd.DatetimeIndex(df.index).dayofweek) // 5 == 1).astype(float)
Run Code Online (Sandbox Code Playgroud)
基本上它所做的只是使用整数除法(//
)来测试它的dayofweek
属性是否DatetimeIndex
小于5.通常这只返回一个True
或False
,但是astype(float)
在最后添加返回1或0而不是布尔值.
小智 5
获取周末指示器的另一种方法是通过where
函数:
df['WEEKDAY'] = np.where((df['DATE']).dt.dayofweek) < 5,0,1)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6555 次 |
最近记录: |