Pandas从apply函数返回DataFrame?

时间:2017-09-14 16:44:03

标签: python python-2.7 pandas

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

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

tryLookup是否有办法让tryLookup返回我要与sdf DataFrame合并的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'>

但那只是抛出

public class CommonLog
{
    public string Break { get; set; }
    public string Cart { get; set; }
    public string Length { get; set; }
}

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

1 个答案:

答案 0 :(得分:0)

尝试将pd.Series转换为带有pandas.Series.to_frame的数据框,如{1}}所示:

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