Mike的Python學院

Data Analysis、Pandas、資料結構、Python

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/27

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

Q:如何新增Pandas DataFrame資料?
1.insert():在指定的欄位位置新增欄位資料,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
df.insert(2, column="engilsh", value=[88, 72, 74, 98])
print("在第三欄的地方新增一個欄位資料")
print(df)
2.append():新增一筆或一列的資料,透過傳入字典來指定各欄位的值,並且會回傳一個新的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.append({
"name": "Henry",
"math": 60,
"chinese": 62
}, ignore_index=True)
print("新增一筆資料")
print(new_df)
3.concat():利用合併多個Pandas DataFrame的方式來新增資料,並且會回傳一個新的Pandas DataFrame資料集,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df1 = pd.DataFrame(grades)
df2 = pd.DataFrame({
"name": ["Henry"],
"math": [60],
"chinese": [62]
})
new_df = pd.concat([df1, df2], ignore_index=True)
print("合併df來新增資料")
print(new_df)
Q:如何排序Pandas DataFrame資料?
1.sort_index():依照索引值來進行排序,並且會回傳一個新的Pandas DataFrame資料集,如下範例:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
df.index = ["s3", "s1", "s4", "s2"]
new_df = df.sort_index(ascending=True)
print("遞增排序")
print(new_df)
new_df = df.sort_index(ascending=False)
print("遞減排序")
print(new_df)
2.sort_values():依照欄位內容來進行排序,並且會回傳一個新的Pandas DataFrame資料集,下面範例以math欄位內容來進行排序:
grades = {
"name": ["Mike", "Sherry", "Cindy", "John"],
"math": [80, 75, 93, 86],
"chinese": [63, 90, 85, 70]
}
df = pd.DataFrame(grades)
new_df = df.sort_values(["math"], ascending=True)
print("遞增排序")
print(new_df)
new_df = df.sort_values(["math"], ascending=False)
print("遞減排序")
print(new_df)
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/11/python-pandas-dataframe-tutorial.html )網站觀看更多精彩內容。
3 0 11838 1