如何更新另一列值与特定值匹配的一列行的值?
How to update the values of one column's row where another column value matches specific value?
我有一个包含四列的数据框 id1
、id2
、config_type
、call_frequency
,但是 id1
和 id2
没关系。
我需要用条件与另一列匹配的特定字符串替换 call_frequency
列的值。
输入:
输出:
基本上我需要在 config_types
匹配时替换相应 call_frequency
列中的值。
{'type2':'string2', 'type3':'string3', 'type4':'string4'}
并且不匹配的值应该保持不变。
我试过了:
df[df.config_type == 'dict_key', 'column'] = 'dict_value'
但它给我错误。
TypeError: 'Series' objects are mutable, thus they cannot be hashed
知道如何解决这个问题吗?
- 使用
loc
.
d = {'type2':'string2', 'type3':'string3', 'type4':'string4'}
for k,v in d.items():
df.loc[df.config_type==k, 'call_frequency'] = v
使用 numpy.where
的替代方法:
import numpy as np
d = {'type2':'string2', 'type3':'string3', 'type4':'string4'}
df["call_frequency"]=np.where(df['config_type'].isin(d), df['config_type'].replace(d), df['call_frequency'])
我有一个包含四列的数据框 id1
、id2
、config_type
、call_frequency
,但是 id1
和 id2
没关系。
我需要用条件与另一列匹配的特定字符串替换 call_frequency
列的值。
输入:
输出:
基本上我需要在 config_types
匹配时替换相应 call_frequency
列中的值。
{'type2':'string2', 'type3':'string3', 'type4':'string4'}
并且不匹配的值应该保持不变。
我试过了:
df[df.config_type == 'dict_key', 'column'] = 'dict_value'
但它给我错误。
TypeError: 'Series' objects are mutable, thus they cannot be hashed
知道如何解决这个问题吗?
- 使用
loc
.
d = {'type2':'string2', 'type3':'string3', 'type4':'string4'}
for k,v in d.items():
df.loc[df.config_type==k, 'call_frequency'] = v
使用 numpy.where
的替代方法:
import numpy as np
d = {'type2':'string2', 'type3':'string3', 'type4':'string4'}
df["call_frequency"]=np.where(df['config_type'].isin(d), df['config_type'].replace(d), df['call_frequency'])