有条件地替换 pandas 数据框中的值 - numpy where behavior
Conditionally replace values in pandas dataframe - numpy where behaviour
我的目标是根据条件替换 pandas 数据框中的某些值。
我发现 numpy where 方法期望第一个参数是布尔值数组,以及以下工作:
def evaluate_array(array_to_evaluate):
output_array = []
for elem in array_to_evaluate:
if elem is None:
output_array.append(True)
else:
output_array.append(False)
return output_array
df['property'] = np.where(
evaluate_array(df['property']),
'The value is None',
df.property
)
问题:
一定有更好的方式来表达上面的代码行!我尝试了以下方法:
df.loc[df.property is None, 'property'] = 'None'
但我收到错误消息:
KeyError: 'cannot use a single bool to index into setitem'
the accepted solution to which 和我自己的工作代码一样冗长!
编辑:
下面评论中提供的一个很好的解决方案适用于我的情况如下:
df = df.fillna(value={'property':'The value is None'})
或更具可读性:
df['property'].fillna('The value is None', inplace=True)
编辑2:
另外,请参阅下面接受的答案以获得另一个很好的解决方案
怎么样
>>> df['property'] = df['property'].fillna('The value is None')
或者,如果 None 是 str
,您可以简单地替换:
>>> df['property'] = df['property'].replace('None','The value is None')
我的目标是根据条件替换 pandas 数据框中的某些值。
我发现 numpy where 方法期望第一个参数是布尔值数组,以及以下工作:
def evaluate_array(array_to_evaluate):
output_array = []
for elem in array_to_evaluate:
if elem is None:
output_array.append(True)
else:
output_array.append(False)
return output_array
df['property'] = np.where(
evaluate_array(df['property']),
'The value is None',
df.property
)
问题:
一定有更好的方式来表达上面的代码行!我尝试了以下方法:
df.loc[df.property is None, 'property'] = 'None'
但我收到错误消息:
KeyError: 'cannot use a single bool to index into setitem'
the accepted solution to which 和我自己的工作代码一样冗长!
编辑: 下面评论中提供的一个很好的解决方案适用于我的情况如下:
df = df.fillna(value={'property':'The value is None'})
或更具可读性:
df['property'].fillna('The value is None', inplace=True)
编辑2: 另外,请参阅下面接受的答案以获得另一个很好的解决方案
怎么样
>>> df['property'] = df['property'].fillna('The value is None')
或者,如果 None 是 str
,您可以简单地替换:
>>> df['property'] = df['property'].replace('None','The value is None')