gpt4 book ai didi

python - 如何从 Pandas 中的另一列中减去字符串类型列的值

转载 作者:太空狗 更新时间:2023-10-29 20:57:30 26 4
gpt4 key购买 nike

我有一个这样的数据框

df
col1 col2 col3
A black berry black
B green apple green
C red wine red

我想从 col2 值中减去 col3 值,结果看起来像

df1
col1 col2 col3
A berry black
B apple green
C wine red

如何使用 pandas 有效地做到这一点

最佳答案

list comprehensionreplacesplit结合使用:

df['col2'] = [a.replace(b, '').strip() for a, b in zip(df['col2'], df['col3'])]
print (df)
col1 col2 col3
0 A berry black
1 B apple green
2 C wine red

如果顺序不重要,将拆分后的值转换为集合并相减:

df['col2'] = [' '.join(set(a.split())-set([b])) for a, b in zip(df['col2'], df['col3'])]
print (df)
col1 col2 col3
0 A berry black
1 B apple green
2 C wine red

或者使用带有if条件和join的生​​成器:

df['col2'] = [' '.join(c for c in a.split() if c != b) for a, b in zip(df['col2'], df['col3'])]

性能:

pic

这是用于生成 perfplot 的设置以上:

def calculation(val):
return val[0].replace(val[1],'').strip()


def regex(df):
df.col2=df.col2.replace(regex=r'(?i)'+ df.col3,value="")
return df

def lambda_f(df):
df["col2"] = df.apply(lambda x: x["col2"].replace(x["col3"], "").strip(), axis=1)
return df

def apply(df):
df['col2'] = df[['col2','col3']].apply(calculation, axis=1)
return df

def list_comp1(df):
df['col2'] = [a.replace(b, '').strip() for a, b in zip(df['col2'], df['col3'])]
return df

def list_comp2(df):
df['col2'] = [' '.join(set(a.split())-set([b])) for a, b in zip(df['col2'], df['col3'])]
return df

def list_comp3(df):
df['col2'] = [' '.join(c for c in a.split() if c != b) for a, b in zip(df['col2'], df['col3'])]
return df


def make_df(n):
d = {'col1': {0: 'A', 1: 'B', 2: 'C'}, 'col2': {0: 'black berry', 1: 'green apple', 2: 'red wine'}, 'col3': {0: 'black', 1: 'green', 2: 'red'}}
df = pd.DataFrame(d)
df = pd.concat([df] * n * 100, ignore_index=True)
return df

perfplot.show(
setup=make_df,
kernels=[regex, lambda_f, apply, list_comp1,list_comp2,list_comp3],
n_range=[2**k for k in range(2, 10)],
logx=True,
logy=True,
equality_check=False, # rows may appear in different order
xlabel='len(df)')

关于python - 如何从 Pandas 中的另一列中减去字符串类型列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54828801/

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