本文介紹了Pandas-通過對(duì)列和索引的值求和來合并兩個(gè)數(shù)據(jù)框的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我想按索引和列合并兩個(gè)數(shù)據(jù)集.
I want to merge two datasets by indexes and columns.
我想合并整個(gè)數(shù)據(jù)集
df1 = pd.DataFrame([[1, 0, 0], [0, 2, 0], [0, 0, 3]],columns=[1, 2, 3])
df1
1 2 3
0 1 0 0
1 0 2 0
2 0 0 3
df2 = pd.DataFrame([[0, 0, 1], [0, 2, 0], [3, 0, 0]],columns=[1, 2, 3])
df2
1 2 3
0 0 0 1
1 0 2 0
2 3 0 0
我已經(jīng)嘗試過這段代碼,但我得到了這個(gè)錯(cuò)誤.我不明白為什么它將軸的大小顯示為錯(cuò)誤.
I have tried this code but I got this error. I can't get why it shows the size of axis as an error.
df_sum = pd.concat([df1, df2])
.groupby(df2.index)[df2.columns]
.sum().reset_index()
ValueError: Grouper and axis must be same length
這就是我預(yù)期的 df_sum 的輸出
This was what I expected the output of df_sum
df_sum
1 2 3
0 1 0 1
1 0 4 0
2 3 0 3
推薦答案
你可以使用:df1.add(df2, fill_value=0)
.它會(huì)將 df2
添加到 df1
中,并且它會(huì)將 NAN
值替換為 0
.
You can use :df1.add(df2, fill_value=0)
. It will add df2
into df1
also it will replace NAN
value with 0
.
>>> import numpy as np
>>> import pandas as pd
>>> df2 = pd.DataFrame([(10,9),(8,4),(7,np.nan)], columns=['a','b'])
>>> df1 = pd.DataFrame([(1,2),(3,4),(5,6)], columns=['a','b'])
>>> df1.add(df2, fill_value=0)
a b
0 11 11.0
1 11 8.0
2 12 6.0
這篇關(guān)于Pandas-通過對(duì)列和索引的值求和來合并兩個(gè)數(shù)據(jù)框的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!