在 Python 中,"replace function" 可以替换等于而不是包含在数据框中的字符串吗?

In Python, can the "replace function" replace strings equal to instead containting in a dataframe?

我有一个从雅虎财经抓取的数据框。我想替换缺失值(标记为“-”),以便我可以将数据框调整为数字。但是,当我使用 replace 函数时,它会很好地从负数中删除“-”。有没有一种方法可以让我只替换数据框中完全等于“-”的字符串?

df[col] = df[col].apply(lambda x: x.replace('-', 'what you want') if x == '-' else x)

您可以对整个数据框或特定列使用替换选项:

#How to replace on a specific column
d = {'col1': [-10.5, 10.5, '-'], 'col2': [3, 4, '-']}
df = pd.DataFrame(d)
df['col1'].replace('-', 'something else')

#How to replace for entire dataframe
d = {'col1': [-10.5, 10.5, '-'], 'col2': [3, 4, '-']}
df = pd.DataFrame(d)
df.replace('-', 'something else')