Mike的Python學院

PYTHON資料分析、Python、Data Analysis、Pandas

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/27

Pandas DataFrame處理雙維度資料方法(3)

Q:如何刪除Pandas DataFrame資料
1.drop(欄位名稱串列,axis=1):刪除指定欄位名稱的欄位,並且會回傳一個新的Pandas DataFrame資料集,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
new_df = df.drop(["math"], axis=1)
print("刪除math欄位")
print(new_df)
2.drop(資料索引串列,axis=0):刪除指定資料索引的資料,並且會回傳一個新的Pandas DataFrame資料集,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
new_df = df.drop([0, 3], axis=0) # 刪除第一筆及第四筆資料
print("刪除第一筆及第四筆資料")
print(new_df)
3.dropna():刪除含有NaN或空值的資料,並且會回傳一個新的Pandas DataFrame資料集,在進行資料清理的時候非常實用,如下範例:
grades = {
"name": ["Mike", "Sherry", np.NaN, "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
new_df = df.dropna()
print("刪除空值後的df")
print(new_df)
4.drop_duplicates():刪除重複的資料,並且會回傳一個新的Pandas DataFrame資料集,同樣最常應用在資料清理的時候,如下範例:
grades = {
"name": ["Mike", "Mike", "Cindy", "John"],
"city": ["Taipei", "Taipei", "Kaohsiung", "Taichung"],
"math": [80, 80, 93, 86],
"chinese": [80, 80, 93, 86]
}
df = pd.DataFrame(grades)
new_df = df.drop_duplicates()
print("刪除重複值後的df")
print(new_df)
Q:如何篩選Pandas DataFrame資料
通常在處理大量的資料集時,有很高的機率會需要利用條件式來篩選所需的資料,這時候就可以利用中括號[]存取欄位來進行資料篩選,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print("篩選math大於80的資料集")
print(df[df["math"] > 80])
另一個最常見的資料篩選情境,就是找出包含特定值的資料集,這時候可以利用Pandas DataFrame的isin()方法(Method)來達成,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print("篩選name欄位包含John的資料集")
print(df[df["name"].isin(["John"])])
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/11/python-pandas-dataframe-tutorial.html )網站觀看更多精彩內容。
2 0 1647 0