Python:在pandas lambda表达式中使用函数

Eda*_*ame 3 python lambda dataframe pandas

我有以下代码,试图找到数据框中"日期"列的小时:

print(df['Dates'].head(3))
df['hour'] = df.apply(lambda x: find_hour(x['Dates']), axis=1)

def find_hour(self, input):
    return input[11:13].astype(float)
Run Code Online (Sandbox Code Playgroud)

其中print(df['Dates'].head(3))的样子:

0    2015-05-13 23:53:00
1    2015-05-13 23:53:00
2    2015-05-13 23:33:00
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

    df['hour'] = df.apply(lambda x: find_hour(x['Dates']), axis=1)
NameError: ("global name 'find_hour' is not defined", u'occurred at index 0')
Run Code Online (Sandbox Code Playgroud)

有谁知道我错过了什么?谢谢!


请注意,如果我将函数直接放在lambda行中,如下所示,一切正常:

df['hour'] = df.apply(lambda x: x['Dates'][11:13], axis=1).astype(float)
Run Code Online (Sandbox Code Playgroud)

zon*_*ndo 9

find_hour在定义之前尝试使用.你只需要切换一下:

def find_hour(self, input):
    return input[11:13].astype(float)

print(df['Dates'].head(3))
df['hour'] = df.apply(lambda x: find_hour(x['Dates']), axis=1)
Run Code Online (Sandbox Code Playgroud)

编辑:帕德里克指出很重要的一点:find_hour()被定义为采用两个参数,self并且input,但是你给它唯一的一个.除了将参数定义为阴影内置函数之外,您应该定义find_hour()为.您可以考虑将其重命名为更具描述性的内容.def find_hour(input):input


Max*_*axU 5

旧货有什么问题.dt.hour

In [202]: df
Out[202]:
                 Date
0 2015-05-13 23:53:00
1 2015-05-13 23:53:00
2 2015-05-13 23:33:00

In [217]: df['hour'] = df.Date.dt.hour

In [218]: df
Out[218]:
                 Date  hour
0 2015-05-13 23:53:00    23
1 2015-05-13 23:53:00    23
2 2015-05-13 23:33:00    23
Run Code Online (Sandbox Code Playgroud)

并且如果您的Date列是字符串类型,则可能需要先将其转换为datetime :

df.Date = pd.to_datetime(df.Date)
Run Code Online (Sandbox Code Playgroud)

要不就:

df['hour'] = int(df.Date.str[11:13])
Run Code Online (Sandbox Code Playgroud)