如何根据字典替换数据列中的值?

How do I replace values in data column according to dictionary?


我需要用引用字典中同名值的值替换数据集列中的值。
所以我的数据看起来像这样(不要注意列名):
data = data[['A?',
       'B',...,]]

字典看起来像这样:

felt_index = {
  "First opt": 1,
  "Second opt": 1,
  "Third opt": 0.72
}

我希望我的专栏看起来像这样:

A? ...
First opt ...
Second opt ...
Third opt ...

看起来像这样:

A? ...
1 ...
1 ...
0.72 ...

我已经尝试了一些解决方案,但没有成功。 我最后尝试的是:

for val in data[['A?']]:        
        data[['A']][val] = felt_index.get(data[['A?']][val])

我得到了这个错误:

TypeError: unhashable type: 'Series'

我不知道怎么解决:(请帮忙。

使用pandas.DataFrame.replace:

new_df = df.replace({"A?": felt_index})
print(new_df)

输出:

     A?  ...
0  1.00  ...
1  1.00  ...
2  0.72  ...

来自pandas.DataFrame.replace的官方文档:

For a DataFrame, nested dictionaries, e.g., {'a': {'b': np.nan}}, are read as follows: look in column 'a' for the value 'b' and replace it with NaN.

如果你想替换那些不在字典中的:

# Sample
           A?  ...
0   First opt  ...
1  Second opt  ...
2   Third opt  ...
3     Non opt  ...

df["A?"] = df["A?"].map(felt_index).replace({np.nan: None})

输出:

     A?  ...
0   1.0  ...
1   1.0  ...
2  0.72  ...
3  None  ...

请注意,由于您想要 None,因此需要 replacedict。如果您想要特定值,请改用 fillna

df["A?"] = df["A?"].map(felt_index).fillna("NO!")

输出:

     A?  ...
0   1.0  ...
1   1.0  ...
2  0.72  ...
3   NO!  ...