[英]Pandas Series Conditionally Change String
我正在嘗試按條件更改 Pandas 系列中的字符串。 如果字符串名稱為“A”,則應為“AA”。 下面的代碼片段有效,但它非常不優雅且效率低下。 正如我所說,我正在通過 Pandas 系列作為參數。 有沒有其他方法可以做到這一點?
def conditions(x):
if x == 'A':
return "AA"
elif x == 'B':
return "BB"
elif x == 'C':
return "CC"
elif x == 'D':
return "DD"
elif x == 'E':
return "EE"
elif x == 'F':
return "FF"
elif x == 'G':
return "GG"
elif x == 'H':
return "HH"
elif x == 'I':
return "I"
elif x == 'J':
return "JJ"
elif x == 'K':
return "KK"
elif x == 'L':
return 'LL'
func = np.vectorize(conditions)
test = func(rfqs["client"])
如果您只是想重復給定的字符串,則可以一次在所有行中將字符串添加到自身。 如果您有其他一些條件,則可以指定該條件並僅將字符串添加到滿足條件的行中。 請參閱此玩具示例:
df = pd.DataFrame({'client': ['A', 'B', 'Z']})
df.loc[df['client'].str.contains('[A-L]'), 'client'] = df['client'] * 2
要得到
client
0 AA
1 BB
2 Z
您可以使用字典來避免所有這些 if elses:
d = {i:2*i for i in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')}
test = rfqs["client"].apply(lambda x: d[x] if x in d else x)
這是另一種方式:
l = list('ABCDEFGHIJKL')
df['col'] = df['col'].mask(df['col'].isin(l),df['col'].str.repeat(2))
與np.where()
df['col'].mul(np.where(df['col'].isin(l),2,1))
使用map()
df['A'].mul(df['A'].map({i:2 for i in l}).fillna(1).astype(int))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.