我有原始的DataFrame(df1)。
我创建了一个新的DataFrame(df2),其中只有第一个(df1)中的一些行。
我向此新的DataFrame(df2)添加了一些列。
现在,我想用我的新内容(df2)首先更新DataFrame(df1)。


所以...我需要合并2个DataFrame,第二个DataFrame具有更多的列和更少的行。

import pandas as pd

print(pd.__version__)
# 0.24.1

index1 = [1, 2, 3, 4]
columns1 = ['a', 'b', 'c']
data1 = [
    ['a1', 'b1', 'c1'],
    ['a2', 'b2', 'c2'],
    ['a3', 'b3', 'c3'],
    ['a4', 'b4', 'c4']]


index2 = [1, 4]
columns2 = ['b', 'c', 'd', 'e']
data2 = [
    ['b1', 'c1', '<D1', 'e1'],
    ['b4', '<C4', 'd4', 'e4']]

df1 = pd.DataFrame(index=index1, columns=columns1, data=data1)
df2 = pd.DataFrame(index=index2, columns=columns2, data=data2)

print(df1)
#     a   b   c
# 1  a1  b1  c1
# 2  a2  b2  c2
# 3  a3  b3  c3
# 4  a4  b4  c4


print(df2)
#     b     c     d   e
# 1  b1    c1   <D1  e1
# 4  b4   <C4    d4  e4

# What I want:
#     a    b    c    d    e
# 1  a1   b1   c1  <D1   e1
# 2  a2   b2   c2  NaN  NaN
# 3  a3   b3   c3  NaN  NaN
# 4  a4   b4  <C4   d4   e4


我尝试过,但是我迷失了所有的.merge.update.concat.join.combine_first等方法和所有参数。如何简单地合并这2个DataFrame

最佳答案

我无法一口气做到这一点,但这应该工作

df1.update(df2)
df1 = df1.merge(df2, how='left')


然后由于某种原因“合并”会重置索引,因此,如果您仍然希望1到4:

df1.index = index1

Out[]:
    a   b    c    d    e
1  a1  b1   c1  <D1   e1
2  a2  b2   c2  NaN  NaN
3  a3  b3   c3  NaN  NaN
4  a4  b4  <C4   d4   e4

关于python - 合并具有不同行数和列数的Pandas 2 DataFrame,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56491572/

10-14 18:34
查看更多