Mike的Python學院

資料結構、Pandas、Data Analysis、Python

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/27

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

Q:如何取得Pandas DataFrame資料?
1.head():取得最前面的n筆資料,並且會回傳一個新的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.head(2)
print(new_df) #取得最前面的兩筆資料
2.tail():取得最後面的n筆資料,並且會回傳一個新的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.tail(3)
print(new_df) #取得最後面的三筆資料
3.中括號[]:在中括號中指定「欄位名稱」或「資料索引值」,來取得所需的資料集,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print(df[["name"]]) #取得單一欄位資料(型別為DataFrame)
print(df[["name", "chinese"]]) #取得多欄位資料(型別為DataFrame)
print(df[0:3]) #取得索引值0~2的資料
4.at[資料索引值,欄位名稱]:利用資料索引值及欄位名稱來取得「單一值」,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print(df.at[1, "math"]) #利用at()方法取得索引值為1的math欄位資料
5.iat[資料索引值,欄位順序]:利用資料索引值及欄位順序來取得「單一值」,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print(df.iat[1, 0]) #取得索引值為1的第一個欄位資料"
5.loc[資料索引值,欄位名稱]:利用資料索引值及欄位名稱來取得「資料集」,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print(df.loc[[1, 3], ["name", "chinese"]]) #取得資料索引值為1和3的name及chinese欄位資料集
6.iloc[資料索引值,欄位順序]:利用資料索引值及欄位順序來取得「資料集」,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
print(df.iloc[[1, 3], [0, 2]]) #取得資料索引值為1和3的第一個及第三個欄位資料集
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/11/python-pandas-dataframe-tutorial.html )網站觀看更多精彩內容。
2 0 359 0