簡體   English   中英

從具有最多數據(非 NA)的三列創建組合列

[英]Create Combined Column From Three Columns With The Most Data (Not NA)

我有如下數據:

import pandas as pd

df = pd.DataFrame(data=[[1,-2,3,0,0], [0,0,0,4,0], [0,0,0,0,5]]).T

df.columns = ['col1', 'col2', 'col3']
    
> df

  col1 col2 col3
    1   0   0
    -2  0   0
    3   0   0
    0   4   0
    0   0   5

我想創建第四個(“Col4”),它采用非零的 col。

所以結果是:

  col1 col2 col3 col4
    1   0   0   1  
    -2  0   0   -2
    3   0   0   3
    0   4   0   4
    0   0   5   5

編輯:如果兩個非零,請始終使用col1 此外,這些數字可能是負數。 我已經更新了df以反映這一點。

使用最大的列是可能的

df['col4'] = df.max(axis=1)

這是一個例子:

def func(a):
  a = set(a)
  assert len(a)==2  # 0 and another number
  for i in a:
    if i!=0:
      return i
df['col4'] = df.apply(func,axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM