简体   繁体   English

我如何有条件串联

[英]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. 我要执行上述操作,但前提是df ['col']满足2个条件,即value的长度== 4且column中的value匹配选项列表之一。

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: 然后,正如@Wen指出的那样:

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

You can use numpy.where method for that. 您可以使用numpy.where方法。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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