我有4個從Excel導入的數據集,包含2013學年,2014年,2015年和2016年的total_budget。所有數據集都有一個共同的列,每所學校(列LAESTAB)。熊貓:從多個數據框提取列到基於公共列名的新數據框
接下來我想要一個新的數據集,其左側是列公共列LAESTAB(4個數據集中的值相同),列總數爲2013,總數爲2014,總數爲2015,總數爲2016(來自不同數據集)。
我也想擺脫其餘的數據,包括那些沒有出現在所有數據集中的學校ID。
我會嘗試進一步闡述它的例子:
下面是Excel中的數據集的一個示例:
>>> print cuts2016.head()
LA_codelocal_authority_name UPIN URN LAESTAB \
0 201 City of London 500000 0.0 2013614
1 202 Camden 500005 0.0 2022095
2 202 Camden 500007 0.0 2022219
3 202 Camden 500012 0.0 2022502
4 202 Camden 500014 0.0 2022603
School Name Academy? Phase Provider Type \
0 Sir John Cass's Foundation Primary School No Primary School
1 Carlton Primary School No Primary School
2 Fleet Primary School No Primary School
3 Rhyl Primary School No Primary School
4 Torriano Primary School No Primary School
MFG protection (+ve) or capping/scaling (-ve) total2016 \
0 35000 1659000
1 68000 1956000
2 -10000 1059000
3 97000 2234000
4 0 2284000
另一張Excel數據集2005:
print cuts2015.head()
LA_code local_authority_name UPIN URN LAESTAB \
0 201 City of London NaN 100000 2013614
1 202 Camden NaN 100008 2022019
2 202 Camden NaN 100009 2022036
3 202 Camden NaN 100010 2022065
4 202 Camden NaN 100011 2022078
school_name Phase Provider Type \
0 Sir John Cass's Foundation Primary School Primary School
1 Argyle Primary School Primary School
2 Beckford Primary School Primary School
3 Brecknock Primary School Primary School
4 Brookfield Primary School Primary School
Basic Entitlement Total Funding Deprivation Total Funding total_pre_MFG \
0 1,206,000 215,000 1,644,000
1 1,333,000 367,000 2,068,000
2 1,482,000 359,000 2,221,000
3 1,234,000 348,000 1,974,000
4 1,436,000 256,000 2,028,000
MFG protection (+ve) or capping/scaling (-ve) total2015 \
0 0 1644000
1 25,000 2093000
2 0 2221000
3 72,000 2046000
4 -58,000 1970000
我需要的最終結果如下(應顯示總計2014和2013):
LAESTAB total2016 total2015 etc...\
2013614 1956000 1644000
2022019 1059000 2093000
2022036 2234000 2221000
2022065 2284000 1970000
...
我試過'減少'如下,但它返回0行×66列。
dataframe_list = [cuts2013, cuts2014, cuts2015, cuts2016]
df_final = reduce(lambda left,right: pd.merge(left,right,on='LAESTAB'), dataframe_list)
它只適用於2個數據集。我能做些什麼來合併4個數據集? '錯誤 TypeError:無法將['left']與塊值進行比較' – edachan
讓我們假設您擁有名爲'dataset_1,dataset_2,dataset_3和dataset_4'的數據集。 一旦合併了'dataset_1'和'dataset_2',讓我們說你得到一個名爲'merged_dataframe'的數據框。 現在將'dataset_3'與'merged_dataframe'合併,並用'dataset_4'重複這個過程。不是最好的想法,但它應該完成這項工作。 –
試圖@ mainul-islam,但返回0行'data_merged2 = pd.merge(data_merged,cuts2014,on =「LAESTAB」)' – edachan