python - 在多列上使用 df.apply 的更好方法是什么?

标签 python pandas

在与 csv 文件编码作斗争之后,我决定进行手动替换一些字符的编码异端。

这是数据框的外观:

df = pd.DataFrame({'a' : 'bÉd encoded',
               'b' : ['foo', 'bar'] * 3,
               'c' : 'bÉd encoded too'})


              a    b                 c
0  bÉd encoded  foo  bÉd encoded too
1  bÉd encoded  bar  bÉd encoded too
2  bÉd encoded  foo  bÉd encoded too
3  bÉd encoded  bar  bÉd encoded too
4  bÉd encoded  foo  bÉd encoded too
5  bÉd encoded  bar  bÉd encoded too

如果我唯一的问题是“a”列,这个函数就足够了:

def force_good_e(row):
    col = row['a']
    if 'É' in col:
        col = col.replace('É','a') 
    return col

df['a'] = df.apply(force_good_e, axis=1)

但是我需要为“c”列提供另一个函数

我对此有所改进:

def force_good_es(row, column):
    col = row[column]
    if 'É' in col:
        col = col.replace('É','a') 
    return col


df['a'] = df.apply(lambda x: force_good_es(x,'a'), axis=1)
df['c'] = df.apply(lambda x: force_good_es(x,'c'), axis=1)

但这让我想知道,是否有更好的方法来做到这一点?

即无需制作一行

df[n] = df.apply(lambda x: force_good_es(x,n), axis=1)

对于需要修复的每个 n 列。

最佳答案

您可以使用str.replace

df['a'] = df['a'].str.replace('É','a')
df['c'] = df['c'].str.replace('É','a')

或者像评论中提到的@wen。

df = df.replace({'É':'a'},regex=True)

关于python - 在多列上使用 df.apply 的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52544000/

相关文章:

python - 值错误 : images do not match when blending pictures in PIL

python - 如何对全局 __builtin__ 对象进行 cythonize?

python - 向 Pandas Dataframe 中的字符串添加前导零

python - Pandas 在数据帧上合并,同时保持相同的行数

python - Plotly 中的等值线 map : colours not showing correctly

python - 浮点到字符串往返测试

python - GAN 判别器否认生成的模型

python - Flask-RESTful 如何添加资源并向其传递非全局数据

python - 解释 “Traceback (most recent call last):”错误

python - 如何以 pandastic 方式更改列顺序(排序)?