[英]How to apply a multiple argument function on a large dataframe with pandas?
[英]How to apply a function with argument to a Pandas dataframe
我正在嘗試刪除數據中的所有重音符號。 我找到了一個函數,但無法一次將其應用於整個數據框。
import unicodedata
import pandas as pd
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
only_ascii = nfkd_form.encode('ASCII', 'ignore')
return only_ascii
data = {'name': ['Guzmán', 'Molly'],
'year': [2012, 2012]}
df = pd.DataFrame(data)
df
如何應用以上功能?
我可以使用pandas read_csv
中的任何參數來實現類似的輸出嗎?
正如其他人指出的那樣,這非常簡單:
df['name'] = df['name'].apply(remove_accents)
另外,如果您使用的是Python 3,我建議您更改remove_accents
函數的最后一行。 only_ascii
返回二進制數據,通常最佳做法是將unicode文本保留為常規(Python 3) str
。
def remove_accents(input_str):
nfkd_form = unicodedata.normalize('NFKD', input_str)
only_ascii = nfkd_form.encode('ASCII', 'ignore')
return only_ascii.decode('utf-8')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.