[英]Create Combined Column From Three Columns With The Most Data (Not NA)
I have data like:我有如下数据:
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
I want to create a fourth ("Col4") that takes the col that is non-zero.我想创建第四个(“Col4”),它采用非零的 col。
So result would be:所以结果是:
col1 col2 col3 col4
1 0 0 1
-2 0 0 -2
3 0 0 3
0 4 0 4
0 0 5 5
EDIT: If two non-zero, always use col1
.编辑:如果两个非零,请始终使用
col1
。 Also, the numbers may be negative.此外,这些数字可能是负数。 I have updated the
df
to reflect this.我已经更新了
df
以反映这一点。
Using the maximum of the columns is a possibility使用最大的列是可能的
df['col4'] = df.max(axis=1)
Here's an example:这是一个例子:
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.