【发布时间】:2018-04-24 23:21:55
【问题描述】:
我有一个示例数据框显示如下。 对于每一行,我想先检查c1,如果它不为null,然后检查c2。通过这种方式,找到第一个非空列并将该值存储到列结果中。
ID c1 c2 c3 c4 result
1 a b a
2 cc dd cc
3 ee ff ee
4 gg gg
我现在正在使用这种方式。但我想知道是否有更好的方法。(列名没有任何模式,这只是示例)
df["result"] = np.where(df["c1"].notnull(), df["c1"], None)
df["result"] = np.where(df["result"].notnull(), df["result"], df["c2"])
df["result"] = np.where(df["result"].notnull(), df["result"], df["c3"])
df["result"] = np.where(df["result"].notnull(), df["result"], df["c4"])
df["result"] = np.where(df["result"].notnull(), df["result"], "unknown)
当有很多列时,这种方法看起来不太好。
【问题讨论】: