Mike的Python學院

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

Mike Ku

Learn Code With Mike品牌創辦人

2021/10/25

Pandas Series處理單維度資料方法(下)

Q:如何修改Pandas Series資料?
要修改Pandas Series物件中的某一筆資料,可以利用資料索引值進行存取後,來修改其中的資料,如下範例:
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"])
phone[1] = "Oppo"
如果有自訂的資料索引值,同樣可以依據資料索引值來進行修改,如下範例:
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"], index=["p1", "p2", "p3", "p4"])
phone["p3"] = "Oppo"
Q:如何取得Pandas Series資料筆數?
通常在做資料分析時,都會需要知道載入的資料筆數,這時候可以透過Pandas Series物件的size屬性(Attribute)來取得,如下範例:
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"])
print(phone.size) # 執行結果4
Q: Pandas Series字串運算方法有哪些?
在文章開頭有提到,Pandas套件就像Excel一樣,能夠對儲存的資料進行處理及操作,最常見的就是字串運算,這邊就擷取幾個Pandas Series物件常用的字串運算方法(Method),包含:
1.upper():將字串轉為大寫
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"])
print(phone.str.upper()) # 將字串資料轉換為大寫
2.lower():將字串轉為小寫
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"])
print(phone.str.lower()) # 將字串資料轉換為小寫
3.contains():搜尋是否包含特定字串
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"])
print(phone.str.contains("Sa")) # 搜尋是否包含特定字串
4.replace():取代為指定的字串
phone = pd.Series(["Apple", "Samsung", "Mi", "Sony"])
print(phone.str.replace("Samsung", "Oppo")) # 將Samsung取代為Oppo
Q: Pandas Series數值運算有哪些方法?
另一個Pandas套件最常應用的地方,就是數值的運算,這邊列舉幾個Pandas Series物件常用的數值運算方法(Method),包含:
1.max():最大值
numbers = pd.Series([22, 5, 10, 12, 6, 30])
print(numbers.max()) # 執行結果30
2.min():最小值
numbers = pd.Series([22, 5, 10, 12, 6, 30])
print(numbers.min()) #執行結果5
3.sum():總和
numbers = pd.Series([22, 5, 10, 12, 6, 30])
print(numbers.sum()) #執行結果85
4.mean():平均數
numbers = pd.Series([22, 5, 10, 12, 6, 30])
print(numbers.mean()) # 執行結果14.166666666666666
5.nlargetst():最大的n個數值
numbers = pd.Series([22, 5, 10, 12, 6, 30])
print(numbers.nlargest(2)) # 最大的2個數值
6.nsmallest():最小的n個數值
numbers = pd.Series([22, 5, 10, 12, 6, 30])
print(numbers.nsmallest(2)) # 最小的2個數值
如果想要學習更多的Python應用教學,歡迎前往Learn Code With Mike( https://www.learncodewithmike.com/2020/10/python-pandas-series-tutorial.html )網站觀看更多精彩內容。
0 0 206 0