[問題] 使用upper()在Dataframe新增一欄資料

看板Python作者 (mini)時間8年前 (2017/12/26 12:29), 編輯推噓2(2012)
留言14則, 3人參與, 8年前最新討論串1/1
Hi 最近在做練習題 有一題是要在Pandas Dataframe新增一欄資料 COUNTRY 欄位country的大寫 程式碼如下: import pandas as pdcars = pd.read_csv('cars.csv', index_col = 0) # Use.apply(str.upper) cars["COUNTRY"] = cars["country"].apply(str.upper) print(cars) Output: https://imgur.com/h7j7QFz
請問一下為什麼apply()裡是放str.upper 整個程式碼又沒有str的宣告 怎麼知道str 就是指每一個country 感謝解答~~~ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 207.181.219.248 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1514262577.A.404.html

12/26 12:43, 8年前 , 1F
內建的喔~
12/26 12:43, 1F

12/26 13:19, 8年前 , 2F
H大 是因為upper是String的method 所以apply裡的
12/26 13:19, 2F

12/26 13:20, 8年前 , 3F
str.upper就會直接指向cars["country"]這一欄的string囉
12/26 13:20, 3F

12/26 13:20, 8年前 , 4F
?
12/26 13:20, 4F

12/26 16:42, 8年前 , 5F
看一下apply的定義: ref: http://bit.ly/2DfumGV
12/26 16:42, 5F

12/26 16:45, 8年前 , 6F
apply的第一個參數是要被各個值叫用的函式
12/26 16:45, 6F

12/26 16:47, 8年前 , 7F
怎麼知道是country是因為cars["country"]就已經先說了
12/26 16:47, 7F

12/27 06:54, 8年前 , 8F
我的想法是 apply 很像 map 會對每個值都放進某個fun
12/27 06:54, 8F

12/27 06:54, 8年前 , 9F
ction處理吼傳回
12/27 06:54, 9F

12/27 06:55, 8年前 , 10F
12/27 06:55, 10F

12/27 09:56, 8年前 , 11F
如果是MapReduce的map那的確行為是一樣
12/27 09:56, 11F

12/27 09:59, 8年前 , 12F
不過Series有map方法不過是做資料結合轉換
12/27 09:59, 12F

12/27 10:00, 8年前 , 13F
之前看R它們也是用apply做函式叫用,感覺是資料圈慣例?
12/27 10:00, 13F

12/27 10:01, 8年前 , 14F
12/27 10:01, 14F
文章代碼(AID): #1QGT0nG4 (Python)