Try   HackMD

資料D13:Pandas DataFrame資料增減/合併

資料增減

利用指派增加欄位資料

DataFrame名稱["新欄位名稱"] = 某個Series
可將該Series放到DataFrame中

利用append增加列資料

DataDrame名稱.append(DataFrame名稱或直接創造)
例如
df.append(pd.DataFrame([[3, 4]], columns = ['a', 'b']))

但此時會讓列索引重複,可以用
DataFrame名稱.reset_index(drop=) 重整index
drop預設為False,此時會新增一個叫index的欄位存放原來index
若True則不會有此欄位

利用del或pop刪除欄位

del DataFrame名稱["欄位名稱"]
DataFrame名稱.pop("欄位名稱")

利用刪除列資料

DataFrame名稱.drop("列索引")

資料合併重組

https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

concat 聯集 -上下合併

pd.concat([DataFrame1, DataFrame2])
同欄位的兩資料上下合併
但可能會有索引重複的問題,需要reset_index
若欄位不同合併,會以聯集為模式,本來沒有的部份填Nan

merge 合併 - 欄位左右合併

pd.merge(DataFrame1(left), DataFrame2(right), how='inner', on=None )

on= 根據的欄位
how= 合併的方法(inner/outer/left/right)

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

join 合併 - 依照相同索引合併+擴充欄位

DataFrame1.join(DataFrame2)
若兩個DataFrame欄位名稱重複則會出現錯誤
須加上lsuffix="", rsuffix=""
表示左右欄位重覆部分各自增加的綴字

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Groupby 分組

DataFrame名稱.groupby("欄位名稱") 根據該欄位名稱 相同的分組
後面可以接某些運算例如.sum()
表示根據該欄位名稱一樣的分成一組 將其他欄位加起來
若根據的欄位超過一個,則將欄位名稱用list包起來

https://zhuanlan.zhihu.com/p/101284491

tags: 資料科學馬拉松 python