EduCoder Pandas合併數據集 第一關:Concat與Append操作


任務描述

本關任務:使用read_csv()讀取兩個csv文件中的數據,將兩個數據集合並,將索引設爲Ladder列,並將缺失值填充爲0

相關知識

Numpy中,我們介紹過可以用np.concatenatenp.stacknp.vstacknp.hstack實現合併功能。Pandas中有一個pd.concat()函數與concatenate語法類似,但是配置參數更多,功能也更強大,主要參數如下。

參數名 說明
objs 參與連接的對象,必要參數
axis 指定軸,默認爲0
join inner或者outer,默認爲outer,指明其他軸的索引按哪種方式進行合併,inner表示取交集,outer表示取並集
join_axes 指明用於其他n-1條軸的索引,不執行並集/交集運算
keys 與連接對象有關的值,用於形成連接軸向上的層次化索引。可以是任意值的列表或數組
levels 指定用作層次化索引各級別上的索引
names 用於創建分層級別的名稱,如果設置了keys和levels
verify_integrity 檢查結果對象新軸上的重複情況,如果發現則引發異常。默認False允許重複
ignore_index 不保留連接軸上的索引,產生一組新索引

pd.concat()可以簡單地合併一維的SeriesDataFrame對象。
Series合併

ser1 = pd.Series(['A', 'B', 'C'], index=[1, 2, 3])
ser2 = pd.Series(['D', 'E', 'F'], index=[4, 5, 6])
pd.concat([ser1,ser2])
Out:
1 A 
2 B 
3 C 
4 D 
5 E 
6 F 
dtype: object
DataFrame合併,將concat的axis參數設置爲1即可橫向合併
df1 = pd.DataFrame([["A1","B1"],["A2","B2"]],index=[1,2],columns=["A","B"])
df2 = pd.DataFrame([["A3","B3"],["A4","B4"]],index=[3,4],columns=["A","B"])
pd.concat([df1,df2])
Out:
   A  B
1 A1 B1 
2 A2 B2 
3 A3 B3 
4 A4 B4

合併時索引的處理

np.concatenatepd.concat最主要的差異之一就是Pandas在合併時會保留索引,即使索引是重複的!

df3 = pd.DataFrame([["A1","B1"],["A2","B2"]],index=[1,2],columns=["A","B"])
df4 = pd.DataFrame([["A1","B1"],["A2","B2"]],index=[1,2],columns=["A","B"])
pd.concat([df3,df4])
Out:
   A  B
1 A1 B1 
2 A2 B2 
1 A3 B3 
2 A4 B4
  1. 如果你想要檢測pd.concat()合併的結果中是否出現了重複的索引,可以設置verify_integrity參數。將參數設置爲True,合併時若有索引重複就會觸發異常。
try: 
pd.concat([df3, df4], verify_integrity=True) 
except ValueError as e: 
print("ValueError:", e)
Out:
ValueError: Indexes have overlapping values: [0, 1]
  1. 有時索引無關緊要,那麼合併時就可以忽略它們,可以通過設置 ignore_index參數爲True來實現。
pd.concat([df3,df4],ignore_index=True)
Out:
 A B 
0 A0 B0 
1 A1 B1 
2 A2 B2 
3 A3 B3
  1. 另一種處理索引重複的方法是通過keys參數爲數據源設置多級索引標籤,這樣結果數據就會帶上多級索引。
pd.concat([df3, df4], keys=['x', 'y'])
Out:
   A B 
x 0 A0 B0 
1 A1 B1 
y 0 A2 B2 
1 A3 B3

join和join_axes參數

前面介紹的簡單示例都有一個共同特點,那就是合併的DataFrame都是同樣的列名。而在實際工作中,需要合併的數據往往帶有不同的列名,而 pd.concat提供了一些參數來解決這類合併問題。

df5 = pd.DataFrame([["A1","B1","C1"],["A2","B2","C2"]],index=[1,2],columns=["A","B","C"])
df6 = pd.DataFrame([["B3","C3","D3"],["B4","C4","D4"]],index=[3,4],columns=["B","C","D"])
pd.concat([df5,df6])
Out:
 A  B  C  D
1 A1  B1 C1 NaN
2 A2  B2 C2 NaN
3 NaN B3 C3 D3
4 NaN B4 C4 D4

可以看到,結果中出現了缺失值,如果不想出現缺失值,可以使用join和join_axes參數。

pd.concat([df5,df6],join="inner") # 合併取交集
Out:
  B C 
1 B1 C1 
2 B2 C2 
3 B3 C3 
4 B4 C4

# join_axes的參數需爲一個列表索引對象
pd.concat([df5,df6],join_axes=[pd.Index(["B","C"])])
Out:
 B C 
1 B1 C1 
2 B2 C2 
3 B3 C3 
4 B4 C4
append()方法

因爲直接進行數組合並的需求非常普遍,所以SeriesDataFrame 對象都支持append方法,讓你通過最少的代碼實現合併功能。例如,df1.append(df2)效果與pd.concat([df1,df2])一樣。但是它和Python中的append不一樣,每次使用Pandas中的append()都需要重新創建索引和數據緩存。

編程要求

data.csv和data1.csv是兩份與各國幸福指數排名相關的數據,爲了便於查看排名詳情,所以需要將兩份數據橫向合併。數據列名含義如下:

列名 說明
Country (region) 國家
Ladder 排名
SD of Ladder 排名的偏差
Positive affect 積極影響
Negative affect 消極影響
Social support 社會福利
Freedom 自由度
Corruption 腐敗程度
Generosity 慷慨程度
Log of GDP per capita 人均GDP的對數
Healthy life expectancy 健康程度
  • 讀取step1/data.csvstep1/data1.csv兩份數據;
  • 首先將兩個數據橫向合併;
  • 將索引設爲排名(Ladder)列;
  • 填充空值爲0
    具體要求請參見後續測試樣例。

請先仔細閱讀右側上部代碼編輯區內給出的代碼框架,再開始你的編程工作!
####測試說明
平臺會對你編寫的代碼進行測試,對比你輸出的數值與實際正確的數值,只有所有數據全部計算正確才能進入下一關。
測試輸入:
無測試輸入
預期輸出:
Country (region) Freedom … Negative affect Social support
Ladder …
1 Finland 5.0 … 10.0 2.0
2 Denmark 6.0 … 26.0 4.0
3 Norway 3.0 … 29.0 3.0
4 Iceland 7.0 … 3.0 1.0
5 Netherlands 19.0 … 25.0 15.0
6 Switzerland 11.0 … 21.0 13.0
7 Sweden 10.0 … 8.0 25.0
8 New Zealand 8.0 … 12.0 5.0
9 Canada 9.0 … 49.0 20.0
10 Austria 26.0 … 24.0 31.0
11 Australia 17.0 … 37.0 7.0
12 Costa Rica 16.0 … 87.0 42.0
13 Israel 93.0 … 69.0 38.0
14 Luxembourg 28.0 … 19.0 27.0
15 United Kingdom 63.0 … 42.0 9.0
16 Ireland 33.0 … 32.0 6.0
17 Germany 44.0 … 30.0 39.0
18 Belgium 53.0 … 53.0 22.0
19 United States 62.0 … 70.0 37.0
20 Czech Republic 58.0 … 22.0 24.0
21 United Arab Emirates 4.0 … 56.0 72.0
22 Malta 12.0 … 103.0 16.0
23 Mexico 71.0 … 40.0 67.0
24 France 69.0 … 66.0 32.0
25 Taiwan 102.0 … 1.0 48.0
26 Chile 98.0 … 78.0 58.0
27 Guatemala 25.0 … 85.0 78.0
28 Saudi Arabia 68.0 … 82.0 62.0
29 Qatar 0.0 … 0.0 0.0
30 Spain 95.0 … 107.0 26.0
… … … … … …
127 Congo (Kinshasa) 125.0 … 95.0 107.0
128 Mali 110.0 … 122.0 112.0
129 Sierra Leone 116.0 … 149.0 135.0
130 Sri Lanka 55.0 … 81.0 80.0
131 Myanmar 29.0 … 86.0 96.0
132 Chad 142.0 … 151.0 141.0
133 Ukraine 141.0 … 44.0 56.0
134 Ethiopia 106.0 … 74.0 119.0
135 Swaziland 113.0 … 57.0 103.0
136 Uganda 99.0 … 139.0 114.0
137 Egypt 129.0 … 124.0 118.0
138 Zambia 73.0 … 128.0 115.0
139 Togo 120.0 … 147.0 149.0
140 India 41.0 … 115.0 142.0
141 Liberia 94.0 … 146.0 127.0
142 Comoros 148.0 … 114.0 143.0
143 Madagascar 146.0 … 96.0 128.0
144 Lesotho 97.0 … 64.0 98.0
145 Burundi 135.0 … 126.0 152.0
146 Zimbabwe 96.0 … 34.0 110.0
147 Haiti 152.0 … 119.0 146.0
148 Botswana 60.0 … 65.0 105.0
149 Syria 153.0 … 155.0 154.0
150 Malawi 65.0 … 110.0 150.0
151 Yemen 147.0 … 75.0 100.0
152 Rwanda 21.0 … 102.0 144.0
153 Tanzania 78.0 … 50.0 131.0
154 Afghanistan 155.0 … 133.0 151.0
155 Central African Republic 133.0 … 153.0 155.0
156 South Sudan 154.0 … 152.0 148.0
[156 rows x 11 columns]

import pandas as pd

def task1():
    #********** Begin **********#
    data=pd.read_csv('step1/data.csv')    #讀取data.csv
    data1=pd.read_csv('step1/data1.csv')  #讀取data1.csv
    result=pd.concat([data,data1],axis=1) #橫向合併
    result=result.T.drop_duplicates().T   #通過兩次轉置刪除重複列
    result.index.name = 'Ladder'          #設置索引名
    result=result.fillna(0)				  #填充空值爲0

    #********** End **********#
    return result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章