Python 根据条件附加到数据框列

Python append to dataframe column based on condition

我想计算数据框的一列中管道符号出现的次数,它等于 5,然后我需要在现有值上附加另一个管道符号 (|)。

df2['smartexpenseid']

0      878497|253919815?HOTEL?141791520780|||305117||
1                                   362593||||35068||
2         |231931871509?CARRT?231940968972||||177849|
3       955304|248973233?HOTEL?154687992630||||93191|
4                                 27984||||5883|3242|
5    3579321|253872763?HOTEL?128891721799|92832814|||
6            127299|248541768?HOTEL?270593355555|||||
7         |231931871509?CARRT?231940968972||||177849|
8                                   831665||||80658||
9              |247132692?HOTEL?141790728905||||6249|

例如:对于第 5 行,(|) 计数为 5,因此它应该向现有值添加另一个 (|),对于其他行,由于计数为 6,我们将其保持原样.有人可以帮我解决这个问题吗?

我试过这些

if df2['smartexpenseid'].str.count('\|')==5:
    df2['smartexpenseid'].append('\|')

这让我出错说 "The truth value of a Series is ambiguous"

还有

a = df2['smartexpenseid'].str.count('\|')
if 5 in a:
    a.index(5)

所以你有 vectorized str methods down. Now you need to conditionally append an extra '|' character. See Pandas section on masking 了解更多信息。

m = df2['smartexpenseid'].str.count('\|') == 5
df2.loc[m, 'smartexpenseid'] = df2['smartexpenseid'][m].values + '|'