我有一个示例数据框:
col1 col2
0 Hello, is it me you're looking for Hello
1 Hello, is it me you're looking for me
2 Hello, is it me you're looking for looking
3 Hello, is it me you're looking for for
4 Hello, is it me you're looking for Lionel
5 Hello, is it me you're looking for Richie
我想更改col1,以便删除col2中的字符串,并返回修改后的数据帧。我还想删除字符串之前和之后的字符1,例如,索引1的所需输出将是:
col 1 col 2
1 Hello, is ityou're looking for me
我尝试使用pd.apply()
,pd.map()
使用.replace()
函数,但我无法让.replace()
使用pd.['col2']
作为参数。我也觉得好像不是最好的方法。
有任何帮助吗?我大部分都是熊猫新手,我正在学习,所以请ELI5。
谢谢!
答案 0 :(得分:1)
我的猜测是,你错过了"轴= 1"所以申请不在列上但在行上
A = """Hello, is it me you're looking for;Hello
Hello, is it me you're looking for;me
Hello, is it me you're looking for;looking
Hello, is it me you're looking for;for
Hello, is it me you're looking for;Lionel
Hello, is it me you're looking for;Richie
"""
df = pd.DataFrame([a.split(";") for a in A.split("\n") ][:-1],
columns=["col1","col2"])
df.col1 = df.apply( lambda x: x.col1.replace( x.col2, "" ) , axis=1)
答案 1 :(得分:1)
为数据帧中的每一行做一些函数可以使用:
df.apply(func, axis=1)
func将每行作为参数
作为系列删除col2中出现的col1可以简单地通过
df['col1'] = df.apply(lambda row: row['col1'].replace(row['col2'],'')
但是前面和前面有1个字符,需要更多的工作
所以定义func:
def func(row):
c1 = row['col1'] #string col1
c2 = row['col2'] #string col2
find_index = c1.find(c2) #first find c2 index from left
if find_index == -1: # not find
return c1 #not change
else:
start_index = max(find_index - 1, 0) #1 before but not negative
end_index = find_index + len(c2) +1 #1 after, python will handle index overflow
return c1.replace(c1[start_index:end_index], '') #remove
然后:
df['col1'] = df.apply(func, axis=1)
*为避免复制警告,请使用:
df = df.assign(col1=df.apply(func, axis=1))
答案 2 :(得分:0)
也许有一种更pythonic或更优雅的方式,但是这就是我上面快速完成的方式。如果您不需要灵活性来操纵字符串,并且修复速度比性能更重要,这将是最好的选择。
我取出了数据框的列作为两个单独的序列
col1Series = df['col1']
col2Series = df['col2']
接下来创建一个空列表来存储最终的字符串值:
rowxList = []
迭代如下以填充列表:
for x,y in zip(col1Series,col2Series):
rowx = x.replace(y,'')
rowxList.append(rowx)
最后,将rowxList作为新列放回原始数据帧中。您可以替换旧列。比较安全的做法是在新列下执行此操作,然后对照原始两列检查输出,然后删除不再需要的旧列:
df['newCol'] = rowxList