简体   繁体   中英

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

I want to do the above, but only if df['col'] meets 2 conditions, namely length of value == 4 and value in column matches one of a list of options.

Apologies if this has been asked before, I have been searching for days and can't find anything comparable.

# 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)

Then, as @Wen pointed out:

# The manipulation.
df.loc[(cond_1 & cond_2), 'col'] = 'str' + df['col'].astype(str)

You can use numpy.where method for that. Here is example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM