我正在创建一个可以处理多个数据集的代码。有些数据集给了我年份,而有些数据集给了我月日日年。我已经有代码将几个月和几天提取到仅仅几年,但是我需要编写一些东西,如果它已经是YYYY格式的话,将使年份不复存在。
if df['year'] **contains four digits YYYY:
df['year']=df['year']
else:
df['year'] = df['monthdayyear'].astype(str).str[:10]
最后,我只想保留YYYY格式的年份
答案 0 :(得分:0)
我相信这就是您要的,如果不是,请注释并编辑您的答案,并给出预期的结果。
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