I have a column Date
of type datetime64[ns]
consisting of one row per date . And two more columns A
and B
. Suppose the dates start from 1st Dec 2019 and goes on till 29th Feb 2020, I wish to copy all the values from column A
to column B
upto a certain date x.
For example, if x = 15th Feb 2020, I need to copy values of A from 1st Dec 2019 to 14th Feb 2020 into column B.
Any help appreciated!
I think you need Series.mask
for copy data less like x
, so mask is created by Series.lt
:
np.random.seed(2020)
rng = pd.date_range('2019-12-01', '2020-02-29')
df = pd.DataFrame({'Date': rng,
'A': np.random.randint(10, size=91),
'B': np.random.randint(10, size=91)})
print (df.head(20))
Date A B
0 2019-12-01 0 5
1 2019-12-02 8 2
2 2019-12-03 3 4
3 2019-12-04 6 3
4 2019-12-05 3 0
5 2019-12-06 3 9
6 2019-12-07 7 8
7 2019-12-08 8 2
8 2019-12-09 0 0
9 2019-12-10 0 6
10 2019-12-11 8 7
11 2019-12-12 9 1
12 2019-12-13 3 7
13 2019-12-14 7 2
14 2019-12-15 2 5
15 2019-12-16 3 9
16 2019-12-17 6 6
17 2019-12-18 5 7
18 2019-12-19 0 9
19 2019-12-20 4 3
x = '2019-12-10'
df['B'] = df['B'].mask(df["Date"].lt(x), df['A'])
print (df.head(20))
Date A B
0 2019-12-01 0 0
1 2019-12-02 8 8
2 2019-12-03 3 3
3 2019-12-04 6 6
4 2019-12-05 3 3
5 2019-12-06 3 3
6 2019-12-07 7 7
7 2019-12-08 8 8
8 2019-12-09 0 0
9 2019-12-10 0 6
10 2019-12-11 8 7
11 2019-12-12 9 1
12 2019-12-13 3 7
13 2019-12-14 7 2
14 2019-12-15 2 5
15 2019-12-16 3 9
16 2019-12-17 6 6
17 2019-12-18 5 7
18 2019-12-19 0 9
19 2019-12-20 4 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.