共計 712 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Python 中,drop 是 pandas 庫中 DataFrame 對象的一個方法,用于刪除 DataFrame 中的行或列。
語法:DataFrame.drop(labels=None, axis=0, index=None, columns=None, inplace=False)
參數說明:
- labels:要刪除的行或列的標簽,可以是單個標簽或標簽列表。
- axis:指定要刪除的軸,axis= 0 表示刪除行,axis= 1 表示刪除列,默認為 0。
- index:要刪除的行的標簽,可以是單個標簽或標簽列表。與 labels 參數二選一。
- columns:要刪除的列的標簽,可以是單個標簽或標簽列表。與 labels 參數二選一。
- inplace:是否在原地修改 DataFrame,默認為 False,即不修改原 DataFrame,而是返回一個新的 DataFrame。
示例:
import pandas as pd
data = {'A': [1, 2, 3, 4, 5],
'B': [6, 7, 8, 9, 10],
'C': [11, 12, 13, 14, 15]}
df = pd.DataFrame(data)
# 刪除行
df.drop(1) # 刪除索引為 1 的行
df.drop([0, 2]) # 刪除索引為 0 和 2 的行
# 刪除列
df.drop('A', axis=1) # 刪除列標簽為 'A' 的列
df.drop(['B', 'C'], axis=1) # 刪除列標簽為 'B' 和 'C' 的列
# 修改原 DataFrame
df.drop('A', axis=1, inplace=True)
注意:drop 方法返回一個新的 DataFrame 對象,原 DataFrame 對象不會被修改,除非設置 inplace 參數為 True。
丸趣 TV 網 – 提供最優質的資源集合!
正文完