如何使用熊猫替换所有列中的所有字符串?

时间:2018-07-01 07:10:49

标签: python python-3.x pandas

在大熊猫中,如何在public async Task<T> GetByIdIncludes(Expression<Func<T, bool>> predicate, string includes = "") { return await _dbContext.Set<T>().Include(includes).Where(predicate).FirstOrDefaultAsync(); } 可能在字符串中的任何位置的所有列中将&amp;替换为'&'?

例如,在“标题”列中,如果有一个值“ Good &amp bad”,如何将其替换为“ Good&bad”?

2 个答案:

答案 0 :(得分:1)

使用replaceregex=True替换子字符串:

df = pd.DataFrame({'A': ['Good &amp; bad', 'BB', 'CC', 'DD', 'Good &amp; bad'],
                   'B': range(5),
                   'C': ['Good &amp; bad'] * 5})

print (df)
                A  B               C
0  Good &amp; bad  0  Good &amp; bad
1              BB  1  Good &amp; bad
2              CC  2  Good &amp; bad
3              DD  3  Good &amp; bad
4  Good &amp; bad  4  Good &amp; bad

df = df.replace('&amp;','&', regex=True)
print (df)
            A  B           C
0  Good & bad  0  Good & bad
1          BB  1  Good & bad
2          CC  2  Good & bad
3          DD  3  Good & bad
4  Good & bad  4  Good & bad

如果只想替换一列:

df['A'] = df['A'].replace('&amp;','&', regex=True)
print (df)
            A  B               C
0  Good & bad  0  Good &amp; bad
1          BB  1  Good &amp; bad
2          CC  2  Good &amp; bad
3          DD  3  Good &amp; bad
4  Good & bad  4  Good &amp; bad

答案 1 :(得分:0)

尝试一下

df['Title'] = titanic_df['Title'].replace("&amp;", "&")