繁体   English   中英

如何根据条件将大熊猫数据框中某个范围内的值替换为同一数据框中的另一个值

[英]How to replace values in a range in a pandas dataframe with another value in the same dataframe based on a condition

如果范围中的值大于零,我想用另一列中的相应值替换数据框的列范围内的值。

我认为这样的简单替换将起作用:

df = df.loc[:,'A':'D'].replace(1, df['column_with_value_I_want'])

但是实际上,除了删除column_with_value_I_want之外,实际上我什么都没做,这是完全不希望的,而且我不确定为什么会这样。

这似乎也不起作用:

df[df.loc[:,'A':'D']] > 0 = df['column_with_value_I_want']

它返回错误: SyntaxError: can't assign to comparison

这似乎应该很简单,但是在尝试了几种不同的方法却无济于事之后,我感到茫然。

我正在使用的数据框看起来像这样:

df = pd.DataFrame({'A' : [1,0,0,1,0,0],
                   'B' : [1,0,0,1,0,1],
                   'C' : [1,0,0,1,0,1],
                   'D' : [1,0,0,1,0,0],
                   'column_with_value_I_want' : [22.0,15.0,90.0,10.,None,557.0],})

不知道如何在Pandas本身中做到这一点,但是如果您陷入numpy并不是那么困难。


如果您很幸运,因此整个DataFrame都是数字形式的,则可以按照以下步骤进行:

import numpy as np

m = df.as_matrix()
>>> pd.DataFrame(
    np.where(np.logical_or(np.isnan(m), m > 0), np.tile(m[:, [4]], 5), m), 
    columns=df.columns)
    A   B   C   D   column_with_value_I_want
0   22  22  22  22  22
1   0   0   0   0   15
2   0   0   0   0   90
3   10  10  10  10  10
4   0   0   0   0   NaN
5   0   557     557     0   557

  • as_matrixas_matrix转换为numpy array
  • np.wherenumpy的三元条件。
  • np.logical_ornumpy的or。
  • np.isnan是检查值是否不是nan
  • np.tile平铺(在这种情况下)将2d单列平铺到矩阵。

不幸的是,如果您的某些列(即使是那些未参与此操作的列)本质上是非数字的,则上述操作将失败。 在这种情况下,您可以执行以下操作:

for col in ['A', 'B', 'C', 'D']:
    df[col] = np.where(df[col] > 0, df[col], df.column_with_value_I_want)

只要5个相关的列都是数字,它就会起作用。

这使用了一个循环(在数字Python中是不满意的),但至少它是在列而不是行上使用的。 假设您的数据长于宽,那么就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM