如何在函数中执行脚本

2024-03-29 08:20:06 发布

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

我试图在一个函数中执行代码,这个函数可以在环境中的任何地方使用,但它不起作用,并给出错误

But when i am using the same code without any function it's working fine. i don't understand why is not working when trying to execute within a function

输入数据

Col1
U_a65839_Jan87Apr88
U_b98652_Feb88Apr88_(2).jpg.pdf
V_C56478_mar89Apr89
NaN
Q_d15634_Apr90Apr91
Q_d15634_Apr90Apr91_(3).jpeg.pdf
S_e15336_may91Apr93
NaN

预期输出:

col2          start_dt     end_Dt
Jan87Apr88    Jan1987      Apr1988
Feb88Apr88    Feb1988      Apr1988
mar89Apr89    mar1989      Apr1989
Apr90Apr91    Apr1990      Apr1991
Apr90Apr91    Apr1990      Apr1991
may91Apr93    may1991      Apr1993

我一直在使用的代码

def newmap(x):
    try:
        df['col2'] = df.col1.str.split("_", expand=True)[2]
        # split first part
        df['start_dt'] = df.File_Path.str[:5]
        # split second part
        df['end_dt'] = df.File_Path.str[5:10]
        # add 19
        df['start_dt'] = df.start_dt.replace({'(\d\d)': r'19\1'}, regex=True)
        df['end_dt'] = df.end_dt.replace({'(\d\d)': r'19\1'}, regex=True)

    except ValueError:
        df['status'] = ValueError


    return df

df = newmap(df) 

运行上述代码时,获取错误

AttributeError: 'Series' object has no attribute 'col1'

请建议