gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:58:50 25 4
gpt4 key购买 nike

我想计算数据帧的列中管道符号出现的次数,它等于 5,然后我需要将另一个管道(|)符号 append 到现有值。

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('\|')

这给我带来了错误,说“系列的真实值(value)不明确”

还有

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

最佳答案

所以你有vectorized str methods向下。现在您需要有条件地 append 一个额外的 '|' 字符。查看 Pandas section on masking了解更多信息。

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

关于Python根据条件追加到数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36021766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com