从损坏的时间戳列中提取年份



我正在使用类似于下面示例数据的pandas数据帧。

我需要能够通过查看时间戳字段中的数据来创建一个新列year。

但是,时间戳字段有点损坏。有时年份无效(见Spa记录(,或者字段中输入了两个条目(见大力水手(。

我使用了一个函数来确定哪些值可能不包含作为起点的值日期。然后利用该函数来确定我应该为新列从哪些值中减去年份。

# Import pandas library
import pandas as pd

# initialize list of lists
data = [['Popeyes', '2021/09/21 : 8:30 PM; 2022/10/21 : 6:30 PM'], ['Apple Store', '2021/09/21 : 10:00 AM']
, ['White Castle', '2022/10/23 : 7:00 AM'], ['Spa', '202233/10/25 : 7:00 AM']
,['Gas', '2022/10/26 : 1:00 PM']
,['Target', '202299/10/27 : 4:00 PM'],['Movie Theater', '2022/10/26 : 1:00 PM']]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Transaction', 'Swipe timestamp'])

# print dataframe.
df
from dateutil.parser import parse
def is_date(string, fuzzy=False):
"""
Return whether the string can be interpreted as a date.
:param string: str, string to check for date
:param fuzzy: bool, ignore unknown tokens in string if True
"""
try: 
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False

df["is_date_check"]=df["Swipe timestamp"].apply(is_date,fuzzy=True)
df
def extract_year(row):
if row['is_date_check'] ==True:
year = df["Swipe timestamp"].str[:4] 
else:
year=''
return year
df['year'] = df.apply (lambda row: extract_year(row), axis=1)
df

您需要将extract_year中的df更改为row

def extract_year(row):
if row['is_date_check'] ==True:
year = row["Swipe timestamp"][:4] # <--- here
else:
year=''
return year
df['year'] = df.apply(extract_year, axis=1)

或使用np.where

df['year'] = np.where(df['is_date_check'], df['Swipe timestamp'].str[:4], '')

最新更新