为什么我在非 'NoneType' 的数据上收到 'NoneType' 类型错误?

Why am I getting a 'NoneType' type error on data that is not a 'NoneType'?

我有一系列函数,这些函数采用 pandas 数据帧,清理数据,然后将其发送到 sqlite 数据库。

以下函数正在创建错误:

def send_to_db(df, event_name):

    print df.describe()

    table_names = {
        'Video Played': 'video_played',
        'Item Information Click': 'item_info_click',
        'Faved': 'faved',
        'Add to Cart': 'add_to_cart',
        'Tap to Replay': 'replay'
    }

    print table_names.get(event_name)

    con = db.connect('/Users/metersky/code/mikmak/vid_score/test.db')
    df.to_sql(table_names.get(event_name), con, flavor='sqlite', if_exists='append')
    con.close()

我得到的错误是TypeError: 'NoneType' object is not iterable

这对我来说很奇怪,原因有二:

1) print df.describe() 给我正确的 pandas 输出,这意味着数据不是 None 在函数

的那一点

2)数据被发送到我验证过的sqlite数据库。所以这意味着数据也不在 None 那里。

为什么我会收到此错误以及我的数据何时会变成 None


回溯:

Traceback (most recent call last):
  File "fetch_data.py", line 139, in <module>
    df, event_name = send_to_db(df, event_name)
TypeError: 'NoneType' object is not iterable

我是这样调用函数的:

for event in event_types:
    print event
    df, event_name = get_data(start_date, end_date, event)

    print "*********" + event_name + " data retrieved"

    df, event_name = data_cleanse(df, event_name)

    print  "*********" + event_name + " data cleansed"

    df, event_name = send_to_db(df, event_name)

    print  "*********" + event_name + " data sent to db"

不是return从你的函数中获取任何东西,但期待一个包含 2 项的元组 (df, event_name):

调用函数时:

df, event_name = send_to_db(df, event_name)

你期望得到一个 2 项的元组。

然而你的函数隐含地returns None因为没有非空return语句

您需要修改您的功能以添加:

return df, event_name

更新:如果你真的不需要你函数中的return值,那么不要不要使用赋值语句左侧的任何内容来调用您的函数。这意味着从函数的结果中解包元组。只需像这样调用您的函数:

send_to_db(df, event_name)

请参阅:Python Packing and Unpacking and Tuples and Sequences 其中说:

This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.