简体   繁体   中英

How to replace the rows in column A with the rows in column B only when column B has values different from NaT in Python?

I am trying to replace the rows in column A with the rows in column B only when column B has values different from NaT in Python.

This is what I did:

import numpy as np
import pandas as pd

query0 = pd.DataFrame.from_dict({'Proposed Date': {0: '2021-01-07 00:00:00',
  1: '2021-01-21 00:00:00',
  2: '2021-01-25 00:00:00',
  3: '2021-01-25 00:00:00',
  4: '2021-01-25 00:00:00',
  5: '2021-01-25 00:00:00',
  6: '2021-01-26 00:00:00',
  7: '2021-01-26 00:00:00',
  8: '2021-01-28 00:00:00',
  9: '2021-01-29 00:00:00'},
 'Start Time1': {0: '17:00',
  1: nan,
  2: '09:45',
  3: '11:45',
  4: '14:45',
  5: '14:45',
  6: '14:00',
  7: '14:20',
  8: '18:15',
  9: nan},
 'Publication Date': {0: '2021-01-12 00:00:00',
  1: 'NaT',
  2: 'NaT',
  3: 'NaT',
  4: 'NaT',
  5: 'NaT',
  6: '2021-01-31 00:00:00',
  7: '2021-01-27 00:00:00',
  8: 'NaT',
  9: '2021-01-31 00:00:00'}})


x = np.isnat(query0['Publication Date'])

for i in range(len(query0)):
    if x == 'False':
       query0['Proposed Date'][i] = query0['Publication Date'][i] 
    else:
       query0['Proposed Date'][i]

Let me give you an example of the desired output only for the first row:

# actual dataset for row 0
         Proposed Date    Start Time1     Publication Date
0  2021-01-07 00:00:00       17:00       2021-01-12 00:00:00

# desired output for row 0

      Proposed Date       Start Time1     Publication Date
0  2021-01-12 00:00:00       17:00       2021-01-12 00:00:00

# do this for every row

However, it does not work.

Can anyone help me with this?

Thanks!

You can try np.where (and covert the columns to datetime before):

query0["Proposed Date"] = pd.to_datetime(query0["Proposed Date"])
query0["Publication Date"] = pd.to_datetime(query0["Publication Date"])

query0["Proposed Date"] = np.where(
    query0["Publication Date"].notna(),
    query0["Publication Date"],
    query0["Proposed Date"],
)

print(query0)

Prints:

  Proposed Date Start Time1 Publication Date
0    2021-01-12       17:00       2021-01-12
1    2021-01-21         NaN              NaT
2    2021-01-25       09:45              NaT
3    2021-01-25       11:45              NaT
4    2021-01-25       14:45              NaT
5    2021-01-25       14:45              NaT
6    2021-01-31       14:00       2021-01-31
7    2021-01-27       14:20       2021-01-27
8    2021-01-28       18:15              NaT
9    2021-01-31         NaN       2021-01-31

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM