使用for loop pandas替换datetime值

2024-03-28 18:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像下面这样的df,但大得多。在lastDate列下面有一些错误的日期,只有在correctDate列中有一些内容时,它们才是不正确的。在

dff = pd.DataFrame(
            {"lastDate":['2016-3-27', '2016-4-11', '2016-3-27', '2016-3-27', '2016-5-25', '2016-5-31'],
             "fixedDate":['2016-1-3', '', '2016-1-18', '2016-4-5', '2016-2-27', ''],
             "analyst":['John Doe', 'Brad', 'John', 'Frank', 'Claud', 'John Doe']
            })

enter image description here

enter image description here 第一个是我拥有的,第二个是循环后我想要的


Tags: frank内容dataframedf错误johnpddoe
1条回答
网友
1楼 · 发布于 2024-03-28 18:11:36

首先将这些列转换为datetime数据类型:

for col in ['fixedDate', 'lastDate']:
    df[col] = pd.to_datetime(df[col])

那你就可以利用

^{pr2}$

例如

import pandas as pd

df = pd.DataFrame( {"lastDate":['2016-3-27', '2016-4-11', '2016-3-27', '2016-3-27', '2016-5-25', '2016-5-31'], "fixedDate":['2016-1-3', '', '2016-1-18', '2016-4-5', '2016-2-27', ''], "analyst":['John Doe', 'Brad', 'John', 'Frank', 'Claud', 'John Doe'] })

for col in ['fixedDate', 'lastDate']:
    df[col] = pd.to_datetime(df[col])

mask = pd.notnull(df['fixedDate'])
df.loc[mask, 'lastDate'] = df['fixedDate']
print(df)

收益率

    analyst  fixedDate   lastDate
0  John Doe 2016-01-03 2016-01-03
1      Brad        NaT 2016-04-11
2      John 2016-01-18 2016-01-18
3     Frank 2016-04-05 2016-04-05
4     Claud 2016-02-27 2016-02-27
5  John Doe        NaT 2016-05-31

相关问题 更多 >