我有一个如下的 pandas 数据框列表,并希望合并/合并它们,以便共享列中的值在所有数据框之间是详尽的。最好的方法是什么?
DF 1:
Col1 | Col2 |
---|---|
BLAH1 | A |
BLAH2 | Z |
DF 2:
Col1 | Col2 | Col3 |
---|---|---|
BLAH2 | Z | B |
BLAH3 | Q | K |
DF 3:
Col1 | Col4 |
---|---|
BLAH2 | C |
BLAH3 | W |
期望的结果
Col1 | Col2 | Col3 | Col4 |
---|---|---|---|
BLAH1 | A | NaN | NaN |
BLAH2 | Z | B | C |
BLAH3 | Q | K | W |
最佳答案
如果键是唯一的,在每个数据帧中,你可以先 concat 然后 groupby:
list_dfs = [df1, df2, df3]
pd.concat(list_dfs).groupby('Col1').first()
一般来说,你可以结合一个reduce
和merge
:
from functools import reduce
# find common columns
commons = reduce(lambda x,y: set(x).intersection(set(y)), list_dfs)
reduce(lambda x,y: x.merge(y, on=commons), list_dfs)
关于python - 将 Pandas 数据框列表合并/合并为一个同时保留给定列中的所有值的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70339028/