简体   繁体   English

Pandas:如何根据另一列替换列中的 Nan 值?

[英]Pandas: How to replace values of Nan in column based on another column?

Given that, i have a dataset as below:鉴于此,我有一个数据集如下:

dict = {
    "A": [math.nan,math.nan,1,math.nan,2,math.nan,3,5],
    "B": np.random.randint(1,5,size=8)
}

dt = pd.DataFrame(dict)

My favorite output is, if the in column A we have an Nan then multiply the value of the column B in the same row and replace it with Nan .我最喜欢的 output 是,如果在A列中我们有一个 Nan 然后乘以同一行中B列的值并将其替换为Nan So, given that, the below is my dataset:因此,鉴于此,以下是我的数据集:

    A  B
  NaN  1
  NaN  1
  1.0  3
  NaN  2
  2.0  3
  NaN  1
  3.0  1
  5.0  3

My favorite output is:我最喜欢的 output 是:

  A  B
  2  1
  2  1
  1  3
  4  2
  2  3
  2  1
  3  1
  5  3

My current solution is as below which does not work:我目前的解决方案如下,它不起作用:

dt[pd.isna(dt["A"])]["A"] = dt[pd.isna(dt["A"])]["B"].apply( lambda x:2*x  )

print(dt)

In your case with fillna在您使用fillna的情况下

df.A.fillna(df.B*2, inplace=True)
df
     A  B
0  2.0  1
1  2.0  1
2  1.0  3
3  4.0  2
4  2.0  3
5  2.0  1
6  3.0  1
7  5.0  3

暂无
暂无

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

相关问题 如何根据另一列中的值用另一列的平均值替换 NaN 值? Pandas - How to replace NaN values with another column's mean based on value in another column? Pandas 如何基于另一列的NaN值设置熊猫数据框中的值? - How set values in pandas dataframe based on NaN values of another column? 如果另一列是NaN,如何替换列中的值? - How to replace values in a column if another column is a NaN? Pandas:根据另一列的键在现有列上映射字典值以替换 NaN - Pandas: map dictionary values on an existing column based on key from another column to replace NaN Pandas 根据以另一列为条件的随机值样本替换 NaN 值 - Pandas Replace NaN values based on random sample of values conditional on another column 根据另一列中的“NaN”值在 Pandas Dataframe 中创建一个新列 - Create a new column in Pandas Dataframe based on the 'NaN' values in another column 如何使用 Pandas 根据同一行中另一列的值替换一列中的 NaN 值? - How to replace NaN value in one column based on the value of another column in the same row using Pandas? 如何基于其他列的某些值替换列的nan值 - How to replace nan values of a column based on certain values of other column 根据 pandas dataframe 中的相邻列将 NaN 值替换为特定文本 - Replace NaN values with specific text based on adjacent column in pandas dataframe pandas Dataframe基于键列,将NaN值替换为以前的值 - pandas Dataframe Replace NaN values with with previous value based on a key column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM