Pandas如何从apply函数中返回DataFrame?

6
sdf = sdf['Name1'].apply(lambda x: tryLookup(x, tdf))
tryLookup是一个函数,目前它接受一个字符串作为参数,该字符串是sdf列中Name1的值。我们使用apply将该函数映射到sdf DataFrame中的每一行。
现在的问题是,tryLookup函数返回的只是一个字符串,有没有办法让它返回一个DataFrame,并将其与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'>

任何帮助都将是重要的,谢谢!

您在寻找 pd.lookup 吗?请参考https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html。 - BENY
1个回答

1

尝试使用 pandas.Series.to_frame 将 pd.Series 转换为 dataframe,文档在这里

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

在这种情况下,sdf 是一个数据框。 - X33

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接