我在為 pandas 中的列應用函式時遇到問題,請參見下面的代碼:
import pandas as pd
#create a dict as below
data_dic = {
"text": ['hello',1,'how are you?',4],
"odd": [0,2,4,6],
"even": [1,3,5,7]
}
#create a DataFrame
df = pd.DataFrame(data_dic)
#define function
def checktext(str1):
if isinstance(str1,str):
return str1.upper()
def checknum(str1):
if isinstance(str1,int):
return str1 1
df['new'] = df['text'].apply(lambda x: checktext(x))
df['new'].head()
我的 df 現在顯示如下:
text odd even new
0 hello 0 1 HELLO
1 1 2 3 None
2 how are you? 4 5 HOW ARE YOU?
3 4 6 7 None
我想為具有“無”值的“新”列中的 2 個單元格應用函式校驗碼。有人可以幫忙嗎?謝謝
uj5u.com熱心網友回復:
IIUC,您可以使用矢量代碼:
# make string UPPER
s = df['text'].str.upper()
# where there was no string, get number 1 instead
df['new'] = s.fillna(df['text'].where(s.isna()) 1)
輸出:
text odd even new
0 hello 0 1 HELLO
1 1 2 3 2
2 how are you? 4 5 HOW ARE YOU?
3 4 6 7 5
也就是說,為了論證,您的 2 個函式可以合并為一個:
def check(str1):
if isinstance(str1,str):
return str1.upper()
elif isinstance(str1,int):
return str1 1
df['new'] = df['text'].apply(check)
uj5u.com熱心網友回復:
你的功能:
def checktext(str1):
if isinstance(str1,str):
return str1.upper()
如果 if 陳述句為假(即 'str1' 不是字串),將回傳 None。默認情況下,回傳值?
def checktext(str1):
if isinstance(str1,str):
return str1.upper()
return str1
uj5u.com熱心網友回復:
首先,您可以使用StringMethods訪問器在沒有任何回圈的情況下轉換為大寫。完成此操作后,您可以輕松處理結果為 NaN 的行:
df['new'] = df['text'].str.upper()
mask = df['new'].isna()
df.loc[mask, 'new'] = df.loc[mask, 'text'] 1
它直接給出:
text odd even new
0 hello 0 1 HELLO
1 1 2 3 2
2 how are you? 4 5 HOW ARE YOU?
3 4 6 7 5
uj5u.com熱心網友回復:
采用:
import numpy as np
df['new'] = df['text'].str.upper().fillna(pd.to_numeric(df['text'],
errors='coerce'
)
.add(1).astype(str))\
.fillna(df['text'])
print(df)
text odd even new
0 hello 0 1 HELLO
1 1 2 3 2.0
2 how are you? 4 5 HOW ARE YOU?
3 4 6 7 5.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/444917.html
