Pandas 从 apply 函数返回 DataFrame?

X33*_*X33 6 python python-2.7 pandas

sdf = sdf['Name1'].apply(lambda x: tryLookup(x, tdf))
Run Code Online (Sandbox Code Playgroud)

tryLookupName1是一个当前接受字符串的函数,该字符串是sdf 列中的值。我们使用 apply 将函数映射到 DataFrame 中的每一行sdf

有没有tryLookup办法返回tryLookup一个我想要与 DataFrame 合并的 DataFrame ,而不是仅返回一个字符串sdftryLookup有一些额外的信息,我想通过将它们作为新列添加到 中的所有行来将其包含在结果中sdf

所以回报tryLookup是这样的:

return pd.Series({'BEST MATCH': bestMatch, 'SIMILARITY SCORE': humanScore})
Run Code Online (Sandbox Code Playgroud)

我尝试过诸如

sdf = sdf.merge(sdf['Name1'].apply(lambda x: tryLookup(x, tdf)), left_index=True, right_index=True)
Run Code Online (Sandbox Code Playgroud)

但这只是抛出

Traceback (most recent call last):
  File "lookup.py", line 160, in <module>
    main()
  File "lookup.py", line 40, in main
    sdf = sdf.merge(sdf['Name1'].apply(lambda x: tryLookup(x, tdf)), left_index=True, right_index=True)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 4618, in merge
    copy=copy, indicator=indicator)
  File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 58, in merge
    copy=copy, indicator=indicator)
  File "C:\Python27\lib\site-packages\pandas\tools\merge.py", line 473, in __init__
    'type {0}'.format(type(right)))
ValueError: can not merge DataFrame with instance of type <class 'pandas.core.series.Series'>
Run Code Online (Sandbox Code Playgroud)

任何帮助都会很棒。谢谢。

Moh*_*OUI 1

尝试将 pd.Series 转换为数据框,如下pandas.Series.to_frame所示:

sdf = sdf.merge(sdf['Sold To Name (10)'].apply(lambda x: tryLookup(x, tdf)).to_frame(), left_index=True, right_index=True)
Run Code Online (Sandbox Code Playgroud)