Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将工作日添加到基于其他列的日期列中_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 3.x 将工作日添加到基于其他列的日期列中

Python 3.x 将工作日添加到基于其他列的日期列中,python-3.x,pandas,dataframe,Python 3.x,Pandas,Dataframe,是否有办法将pandas数据框中的日期字段增加另一列中指定的工作日数 np.random.seed(10) df = pd.DataFrame({'Date':pd.date_range(start=dt.datetime(2020,7,1), end = dt.datetime(2020,7,10))}) df['Offset'] = np.random.randint(0,10, len(df)) Date Offset 0 2020-07-01 9 1 20

是否有办法将pandas数据框中的日期字段增加另一列中指定的工作日数

np.random.seed(10)
df = pd.DataFrame({'Date':pd.date_range(start=dt.datetime(2020,7,1), end = dt.datetime(2020,7,10))})
df['Offset'] = np.random.randint(0,10, len(df))

        Date  Offset
0 2020-07-01       9
1 2020-07-02       4
2 2020-07-03       0
3 2020-07-04       1
4 2020-07-05       9
5 2020-07-06       0
6 2020-07-07       1
7 2020-07-08       8
8 2020-07-09       9
9 2020-07-10       0
我希望这能起作用,但它会抛出错误:

df['Date'] + pd.tseries.offsets.BusinessDay(n = df['Offset']) 
TypeError:
n
参数必须是整数,已获取


pd.to_timedelta
不支持工作日。

正如我在评论中提到的,您正在尝试将整个序列作为整数传递。相反,您希望按行显示函数:

df['your_answer'] = df.apply(lambda x:x['Date'] + pd.tseries.offsets.BusinessDay(n= x['Offset']), axis=1)

df
        Date  Offset your_answer
0 2020-07-01       9  2020-07-14
1 2020-07-02       7  2020-07-13
2 2020-07-03       3  2020-07-08
3 2020-07-04       2  2020-07-07
4 2020-07-05       7  2020-07-14
5 2020-07-06       7  2020-07-15
6 2020-07-07       7  2020-07-16
7 2020-07-08       2  2020-07-10
8 2020-07-09       1  2020-07-10
9 2020-07-10       0  2020-07-10
细分的代码行:

# notice how this returns every value of that column
df.apply(lambda x:x['Date'], axis=1)

0   2020-07-01
1   2020-07-02
2   2020-07-03
3   2020-07-04
4   2020-07-05
5   2020-07-06
6   2020-07-07
7   2020-07-08
8   2020-07-09
9   2020-07-10

# same thing with `Offset`
df.apply(lambda x:x['Offset'], axis=1)
0    9
1    7
2    3
3    2
4    7
5    7
6    7
7    2
8    1
9    0

因为接受整数而不是级数。我们将
apply()
中的两列一起使用-就好像您正在将
Offset
列中的每个数字循环到
Offset中一样。BusinessDay()
函数

df['Offset']
是一个序列而不是一个整数,您试图用整个序列来偏移一个值,因此出现了错误。您可能希望查看
apply()
,并尝试在那里找到解决方案!另外,
.apply
对于大型数据帧来说可能非常慢。如果您有许多行,但只有少量的唯一偏移量,那么按偏移量分组要高效得多:并对每个组应用一个偏移量,然后组合结果。太棒了!非常感谢