gpt4 book ai didi

python - 删除一列中的 char/str 作为从另一列中删除不同 str 的条件 - DF Pandas

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

我有一个包含两列的数据框(我们称之为my_df)。

启动示例:

my_df = pd.DataFrame({'first_col':['theTable','aChair','Lamp','intheCup','aBottle','theGlass'],'second_col':['itisBig','isSmall','itisBright','itisDark','isRed', 'itisWhite']})

给出:

   first_col  second_col
0 theTable itisBig
1 aChair isSmall
2 Lamp itisBright
3 intheCup itisDark
4 aBottle isRed
5 theGlass itisWhite

我想删除 first_col 中每个字符串开头的字母“the”。此外,当且仅当满足此条件时,应从 second_col it”强>

结果应该是只有行 0, 5 会受到影响,其中“the”和“it”相应地从第一列和第二列中删除:

   first_col   second_col
0 Table isBig
1 aChair isSmall
2 Lamp itisBright
3 intheCup itisDark
4 aBottle isRed
5 Glass isWhite

请注意,second_col 中的第 2 行和第 3 行没有更改(仍然是:“itisBright”/“itisDark”),因为第一个_col 中出现“the”的条件不满足。

到目前为止,我知道如何分别删除每个条件“the”和“it”:

my_df['first_col'] = my_df['first_col'].str.replace('the','')
my_df['second_col'] = my_df['second_col'].str.replace('it','')

但这可不好!因为这里没有依赖关系。

有人知道如何应用上述条件,以便使用 PANDAS 同时且独立地删除这些字符串吗?

最佳答案

你走在正确的道路上。基本上,您只需要创建一个关于要修改哪些行的 bool 过滤器,然后将这些修改仅应用于这些行。

import pandas as pd

my_df = pd.DataFrame({'first_col':['theTable','aChair','Lamp','intheCup','aBottle','theGlass'],'second_col':['itisBig','isSmall','itisBright','itisDark','isRed', 'itisWhite']})

changes = my_df['first_col'].str.startswith('the')

my_df.loc[changes, 'first_col'] = my_df.loc[changes, 'first_col'].str.replace('the','')
my_df.loc[changes, 'second_col'] = my_df.loc[changes, 'second_col'].str.replace('it','')

关于python - 删除一列中的 char/str 作为从另一列中删除不同 str 的条件 - DF Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43449372/

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