【问题标题】:I am trying to write an "if then" statement. If df['time'] is in format YYYY then df['time']=df['year']. Else df['time']=df['date2']我正在尝试写一个“如果那么”声明。如果 df['time'] 格式为 YYYY,则 df['time']=df['year']。否则 df['time']=df['date2']
【发布时间】:2019-09-24 20:19:18
【问题描述】:

我正在创建一个适用于多个数据集的代码。有些数据集给我年份,有些给我月-日-年。我已经有代码可以将月份和日期提取到几年,但我需要编写一些东西,如果它已经是 YYYY 格式,那么它会留下几年。

if df['year'] **contains four digits YYYY:
 df['year']=df['year']

else:
 df['year'] = df['monthdayyear'].astype(str).str[:10]

最后,我希望只剩下 YYYY 格式的年份

【问题讨论】:

  • 你能提供两个输入和不同输出的例子吗?
  • 使用正则表达式?
  • 或者只获取长度 -- 如果是 4 个字符,那么它就是年份。
  • df['year'] = np.where(condition, df['year'], df['monthdayyear'].astype(str).str[:10]`.
  • 如果 DF 是内部一致的,那么您只需要在第一行使用 try/except 来确定格式,然后再应用于 DF 的其余部分。你显然也可以使用infer_datetime_format

标签: python pandas datetime


【解决方案1】:

我相信这就是您所要求的,如果不是,请使用您的预期输出评论并编辑您的答案。

import pandas as pd
import numpy as np
a = {'year':[1990,1923,1904,'not4digits','not4digits',2001],'monthdayyear':[1990,1923,1904,20140901,20180305,2001]}
df = pd.DataFrame(a)
print(df)
df['year'] = np.where(len(df['year']) == 4, df['year'],df['monthdayyear'].astype(str).str[:10])
print(df)

应用条件前的输出:

         year  monthdayyear
0        1990          1990
1        1923          1923
2        1904          1904
3  not4digits      20140901
4  not4digits      20180305
5        2001          2001

应用np.where 后的输出,其中不满足条件且year 列中的值被monthdayyear 列中的值替换:

       year  monthdayyear
0      1990          1990
1      1923          1923
2      1904          1904
3  20140901      20140901
4  20180305      20180305
5      2001          2001

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2022-08-17
    • 2023-01-09
    • 2018-10-22
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多