[英]How Do I Conditionally Concatenate
>>> df = pd.DataFrame({'col':['a',0]})
>>> df
col
0 a
1 0
>>> df['col'] = 'str' + df['col'].astype(str)
>>> df
col
0 stra
1 str0
我要執行上述操作,但前提是df ['col']滿足2個條件,即value的長度== 4且column中的value匹配選項列表之一。
抱歉,如果以前有人問過我,我已經搜索了幾天,找不到任何可比較的東西。
# The list of options
l = ['aaaa']
# The filtering conditions
cond_1 = df['col'].apply(lambda x: len(str(x)) == 4)
cond_2 = df['col'].isin(l)
然后,正如@Wen指出的那樣:
# The manipulation.
df.loc[(cond_1 & cond_2), 'col'] = 'str' + df['col'].astype(str)
您可以使用numpy.where方法。 這是例子
df = pd.DataFrame({'col':['abcd',0]})
df['col'] = df['col'].astype(str)
df['col'] = np.where(df['col'].str.len() == 4, df['col'] + 'b', df['col'] + 'a')
print(df)
# col
# 0 abcdb
# 1 0a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.