簡體   English   中英

合並超過2個python熊貓數據框

[英]Merge of more than 2 python pandas data frames

我有一些這樣的數據幀

num  a    --  num  b    --  num  c    --   num  d
101  0        101  1        102  0         101  1
102  1        103  1        103  0         102  0
103  0        104  0        104  1         103  1
104  0        105  0        105  1         104  1
105  1        107  1        106  1         106  0
106  1        108  1        107  1         107  0

我將它們放在稱為框架的陣列中。 我想做類似pd.concat(frames)的東西,結果

num   a   b   c   d
101   0   1  Nan  1
102   1  Nan  0   0
103   0   1   0   1
104   0   0   1   1
105   1   0   1  Nan
106   1  Nan  1   0
107  Nan  1   1   0
108  Nan  1  Nan Nan

但我認為我應該使用pd.mergenum設置為聯接列。 使用合並我認為我只能合並2個數據幀,是否應該在循環中使用它合並所有數據幀? 還是可以用concat做到這一點,或者還有其他(更好的)方法嗎?

更新:

dfs = []

data = """\
num  a
101  0
102  1
103  0
104  0
105  1
106  1
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

data = """\
num  b
101  1
103  1
104  0
105  0
107  1
108  1
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

data = """\
num  c
102  0
103  0
104  1
105  1
106  1
107  1
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

data = """\
num  d
101  1
102  0
103  1
104  1
106  0
107  0
"""
dfs.append(pd.read_csv(io.StringIO(data), delim_whitespace=True))

讓我們將num設置為索引:

for i in range(len(dfs)):
    dfs[i].set_index('num', inplace=True)


df = pd.concat(dfs, axis=1)

收益率:

In [116]: df
Out[116]:
       a    b    c    d
num
101  0.0  1.0  NaN  1.0
102  1.0  NaN  0.0  0.0
103  0.0  1.0  0.0  1.0
104  0.0  0.0  1.0  1.0
105  1.0  0.0  1.0  NaN
106  1.0  NaN  1.0  0.0
107  NaN  1.0  1.0  0.0
108  NaN  1.0  NaN  NaN

舊答案:

嘗試pd.concat(..., axis = 1 ):

pd.concat(frames, axis=1)

它將按索引水平連接框架,因此您可能需要預先設置適當的索引

除了pd.concat ,您還可以使用pd.merge

import pandas as pd
import io
a = pd.read_csv(
    io.StringIO(
        "num,a\n101,0\n102,1\n103,0\n104,0\n105,1\n106,1\n"
    ),
    header = 0
)

b = pd.read_csv(
    io.StringIO(
        "num,b\n101,1\n103,1\n104,0\n105,0\n107,1\n108,1\n"
    ),
    header = 0
)

c = pd.read_csv(
    io.StringIO(
        "num,c\n102,0\n103,0\n104,1\n105,1\n106,1\n107,1\n"
    ),
    header = 0
)

d = pd.read_csv(
    io.StringIO(
        "num,d\n101,1\n102,0\n103,1\n104,1\n106,0\n107,0\n"
    ),
    header = 0
)

mylist = [a, b, c, d]

for i in range(4):
    if i == 0:
        result = mylist[i]
    else:
        result = pd.merge(
            result,
            mylist[i],
            how = 'outer',
            on = 'num'
        )

然后您將得到結果。

In [14]: result
Out[14]: 

   num    a    b    c    d
0  101  0.0  1.0  NaN  1.0
1  102  1.0  NaN  0.0  0.0
2  103  0.0  1.0  0.0  1.0
3  104  0.0  0.0  1.0  1.0
4  105  1.0  0.0  1.0  NaN
5  106  1.0  NaN  1.0  0.0
6  107  NaN  1.0  1.0  0.0
7  108  NaN  1.0  NaN  NaN

暫無
暫無

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

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