我正在创建一个代码,它将在几个数据集上工作。有些数据集给出了年份,有些数据集给出了月-日-年。我已经有代码来提取月份和日期到年,但是我需要写一些东西,如果它已经在YYYY格式中,我需要写一些东西来离开年份。
if df['year'] **contains four digits YYYY:
df['year']=df['year']
else:
df['year'] = df['monthdayyear'].astype(str).str[:10]最终,我希望只保留YYYY格式的剩余年份
发布于 2019-09-25 04:30:27
我相信这就是你所要求的,如果不是,请评论并编辑你的答案,使其具有你的预期输出。
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 2001https://stackoverflow.com/questions/58087571
复制相似问题