python - Pandas 从应用函数返回 DataFrame?

标签 python python-2.7 pandas

sdf = sdf['Name1'].apply(lambda x: tryLookup(x, tdf))

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

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

所以 tryLookup 的返回是这样的:

return pd.Series({'BEST MATCH': bestMatch, 'SIMILARITY SCORE': humanScore})

我试过类似的东西

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

但这只是抛出

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'>

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

最佳答案

尝试使用 pandas.Series.to_frame 将 pd.Series 转换为数据帧,如记录 here :

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

关于python - Pandas 从应用函数返回 DataFrame?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46224451/

相关文章:

python - 如何在 python 中使用 pandas 获取所有重复项的列表?

python - 将 pandas 列中的关键字与另一个元素列表匹配

python - 使用 python 无需 protobuf 实时解析 GTFS

python - 递归错误: I'm looking for a way to reduce the number of the loop

python - 从另一个文件导入和更改变量

python - 函数在 Iron Python (Python(x,y) Spyder2 IDE) 中运行,但不在 Python 2.7 控制台中运行

python - 计算 pandas 列直到最后

python - pandas iterrows 和循环计数器的问题

python - cv2.drawContours 没有显示正确的颜色

python - 用反斜杠错误替换字符 - Python