簡體   English   中英

合並具有不同行數和列數的Pandas 2 DataFrame

[英]Merge Pandas 2 DataFrame, with different number of rows and columns

  1. 我有原始的DataFramedf1 )。
  2. 我創建了一個新的DataFramedf2 ),其中只有第一個( df1 )的一些行。
  3. 我向這個新的DataFramedf2 )添加了一些列。
  4. 現在,我想用我的新內容( df2 )更新第一個DataFramedf1 )。

所以...我需要合並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等方法和所有參數。 我怎樣才能簡單地合並這兩個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM