Pandas - Vlookup - Duplicate values in search column

情到浓时终转凉″ 提交于 2020-04-18 12:10:08

问题


I am trying to mimic a v lookup (excel function) in Pandas ( using test data sets the merge function seems to work) - but I do have question regarding the example here https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html . If you look at the first example it mergers the two df's, the output has more columns and more ROWS. I would just want to return a new column - like how a v lookup works. non the less , when I try my code even for the above I get this error:

agingdf = agingdf.merge(plannerdf, left_on ='Cust_PO_Number', right_on='Cust_PO_Number')

ValueError: The column label 'Cust_PO_Number' is not unique.
For a multi-index, the label must be a tuple with elements corresponding to each level.

Below is an open ticket that seems similar to my issues, but had no resolution.

https://github.com/pandas-dev/pandas/issues/20769

I apologize if this is vague, I can't upload the df and excel file because it is for work and the test DF's I tried did not throw the same error.

At the end of the day I just want to do a vlookup with pandas, and the vlookup values may be duplicate, so in that case just whatever duplicate value got hit first thats the value that would return in the new column.

Below, is an example df to help you imagine what I mean by duplicates in Cust_PO_Number

a = {'Cust_PO_Number': ['A', 'B', 'C', 'C'], 'ColumnB': [1,2,3,4]}
b = {'Cust_PO_Number': ['A', 'B', 'C', 'C'], 'Column_That_I_Want_added': [2,3,4,5]}
df = pd.DataFrame(data=a)
df2 = pd.DataFrame(data=b)

desired df
c = {'ColumnA': ['A', 'B', 'C', 'C'], 'ColumnB': [1,2,3,4], 'MatchedColumn', [2,3,4,5]}

desireddf = pd.DataFrame(data=c)

Now to explore multi- level columns

print(plannerdf.columns)
MultiIndex(levels=[['Cust_PO_Number', 'Department']],
           labels=[[0, 1]])

来源:https://stackoverflow.com/questions/55582808/pandas-vlookup-duplicate-values-in-search-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!