【问题标题】:How to replace with values with adjacent column using pandas如何使用熊猫用相邻列的值替换
【发布时间】:2020-05-01 23:39:42
【问题描述】:

我有数据框,df1,

外部连接后df在下方

df1 有 4 列 ['A','B','C','D']

ID,A,B,C,D
1,Nan,Nan,c,d
1,a,b,c,d
  • 我需要将 df['A'] 中的 Nan 值替换为 df['C']
  • 我需要将 df['B'] 中的 Nan 值替换为 df['D']

预期低于

ID,A,B,C,D
1,c,d,c,d
1,a,b,c,d

在第一行 df['A'] 替换为 df['C'],如果 df['A'] 则只需要检索 df['A']

第一行 df['B'] 替换为 df['D'],如果 df['B'] 则只需要检索 df['D']

【问题讨论】:

  • 使用bfill(axis=1)
  • 如果你有:[NaN, b, NaN, d],或[a, NaN, NaN, d]
  • @jcaliz,我不知道它是 [NaN, b, NaN, d]
  • 只要确保涵盖所有情况,第二个呢?
  • 好的,在这个当前的数据集中它不存在,但它可能会在以后出现

标签: python pandas dataframe


【解决方案1】:

您需要用第二列填充该列,一种方法是fillna 指定value 参数:

df.A.fillna(value=df.C, inplace=True)
df.B.fillna(value=df.D, inplace=True)

如果由于某种原因您有很多列并且想要继续使用第二列上的值填充 NaN,则在第一列 n-2 上使用 for 循环

columns = ['A', 'B', 'C', 'D']

for i in range(len(columns)-2):
    df[columns[i]].fillna(df[columns[i+2]], inplace=True)

【讨论】:

  • df.bfill(axis=1, inplace=True)
  • 我已经更新了问题,你能检查一下吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2018-06-17
  • 1970-01-01
  • 2018-11-19
  • 2018-11-04
  • 1970-01-01
  • 2022-12-23
相关资源
最近更新 更多