Pandas,将两个列中的唯一值合并为一个列,同时保持顺序



我有如下所示的四列数据。列1中存在一些值,列1中的一些值再次在列3中重复。我想将列1与列3合并,同时从列3中删除重复项。我还想保持列的顺序。列1与列2相关联,列3与列4相关联,所以如果我能在归并过程中将列1的项移动到列2,将列3的项移动到列4,那就太好了。如有任何帮助,不胜感激。

输入表:

54822105

将输入表分成左右两部分后,我们可以很简单地使用布尔索引将左手项与不重复的右手项连接起来:

import pandas as pd
# this initial section only recreates your sample input table
from io import StringIO
input = pd.read_table(StringIO("""| Item  | Price | Item | Price |
|-------|-------|------|-------|
| Car   | 105   | Truck| 54822 |
| Chair |  20   | Pen  |     1 |
| Cup   |   2   | Car  |   105 |
|       |       | Glass|     1 |
"""), ' *| *', engine='python', usecols=[1,2,3,4], skiprows=[1], keep_default_na=False)
input.columns = list(input.columns[:2])*2
# now separate the input table into the left and right part
left  = input.iloc[:,:2].replace("", pd.NA).dropna().set_index('Item')
right = input.iloc[:,2:]                            .set_index('Item')
# finally construct the output table by concatenating without duplicates
output = pd.concat([left, right[~right.index.isin(left.index)]])

Price
Item        
Car      105
Chair     20
Cup        2
Truck  54822
Pen        1
Glass      1

最新更新