gpt4 book ai didi

python - Pandas 使用 If 语句逐行进行

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:07 25 4
gpt4 key购买 nike

我不确定这是否是最好的标题,如果其他人对标题有更好的想法,我愿意提出建议。

假设我有一个如下所示的数据框:

df2

A section
0 <fruit>
1 apple
2 orange
3 pear
4 watermelon
5 </fruit>
6 <furniture>
7 chair
8 sofa
9 table
10 desk
11 </furniture>

我想要的是一个如下所示的数据框:

             A     section
0 <fruit> fruit
1 apple fruit
2 orange fruit
3 pear fruit
4 watermelon fruit
5 </fruit> fruit
6 <furniture> furniture
7 chair furniture
8 sofa furniture
9 table furniture
10 desk furniture
11 </furniture> furniture

有没有办法做到这一点?我考虑过使用 if 语句逐行处理,但在执行此操作时我遇到了 bool 逻辑问题。

编辑#1:

下面发布的这个解决方案解决了我的问题。

解决方法:

df['section']=pd.Series(np.where(df.A.str.contains('<'),df.A.str.replace('<|>|/',''),np.nan)).ffill()

如果我有这样的数据怎么办?我想要相同的结果。

                                       A          section
0 <fruit>
1 <fruit_1>apple</fruit_1>
2 <fruit_2>orange</fruit_2>
3 <fruit_3>pear</fruit_3>
4 <fruit_4>watermelon</fruit_4>
5 </fruit>
6 <furniture>
7 <furniture_1>chair</furniture_1>
8 <furniture_2>sofa</furniture_2>
9 <furniture_3>table</furniture_3>
10 <furniture_4>desk</furniture_4>
11 </furniture>

最佳答案

IIUC使用contains查找行,并在np.where赋值,然后使用ffill填充np.nan

df['section']=pd.Series(np.where(df.A.str.contains('<'),df.A.str.replace('<|>|/',''),np.nan)).ffill()
df
Out[1003]:
A section
0 <fruit> fruit
1 apple fruit
2 orange fruit
3 pear fruit
4 watermelon fruit
5 </fruit> fruit
6 <furniture> furniture
7 chair furniture
8 sofa furniture
9 table furniture
10 desk furniture
11 </furniture> furniture

如果你想更精确/具体/更严格,你还可以使用 startswithendswith 检查字符串的开始和结束。

df1['Section'] = pd.Series(np.where(df1.A.str.startswith('<') & df1.A.str.endswith('>'), df1.A.str.replace('<|>|/',''), np.nan)).ffill()

关于python - Pandas 使用 If 语句逐行进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52032112/

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