pandas 将数据帧日期行转换为周末/非周末值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32278728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert dataframe date row to a weekend / not weekend value
提问by Raul
I have a dataframe with a DATE row and I need to convert it to a row of value 1 if the date is a weekend day and 0 if it is not.
我有一个带有 DATE 行的数据框,如果日期是周末,我需要将其转换为值为 1 的行,如果不是,则将其转换为 0。
So far, I converted the data to weekdays
到目前为止,我将数据转换为工作日
df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek
It's there a way to create this "WEEKEND" row without functions?
有没有办法在没有函数的情况下创建这个“WEEKEND”行?
Thanks!
谢谢!
回答by dagrha
Here's the solution I've come up with:
这是我想出的解决方案:
df['WEEKDAY'] = ((pd.DatetimeIndex(df.index).dayofweek) // 5 == 1).astype(float)
Essentially all it does is use integer division (//) to test whether the dayofweekattribute of the DatetimeIndexis less than 5. Normally this would return just a Trueor False, but tacking on the astype(float)at the end returns a 1 or 0 rather than a boolean.
本质上它所做的就是使用整数除法 ( //) 来测试 的dayofweek属性是否DatetimeIndex小于 5。通常这将只返回 a Trueor False,但astype(float)在末尾添加 1 或 0 而不是布尔值。
回答by Vivek Payasi
One more way of getting weekend indicator is by first converting the date column to day of the week and then using those values to get weekend/not weekend. This can be implemented as follows:
获取周末指示器的另一种方法是首先将日期列转换为星期几,然后使用这些值来获取周末/非周末。这可以按如下方式实现:
df['WEEKDAY'] = pandas.to_datetime(df['DATE']).dt.dayofweek # monday = 0, sunday = 6
df['weekend_indi'] = 0 # Initialize the column with default value of 0
df.loc[df['WEEKDAY'].isin([5, 6]), 'weekend_indi'] = 1 # 5 and 6 correspond to Sat and Sun
回答by Daniel Ben-David
One more way of getting weekend indicator is by wherefunction:
获取周末指标的另一种方法是按where功能:
df['WEEKDAY'] = np.where((df['DATE']).dt.dayofweek) < 5,0,1)

