【问题标题】:How to merge the values coming from 4 different columns into one fina column如何将来自 4 个不同列的值合并到一个 fina 列中
【发布时间】:2022-11-03 00:39:15
【问题描述】:

我有一个像下面这样的 daframe:

str, mpr, cta, mpt 列都是相同的,但对于每条记录,我在这 4 列中只有 1 列有值。

如何将这 4 列合并为仅 1 列,如下面的输出:

id     str     mpr     cta      mpt
 1     10      null    null     null
 2    null     11      null     null
 3    null     null    6        null
 4    null     null    null     1

输出:

id  final
 1   10
 2   11
 3   6
 4   1

如您所见,final 列将始终具有来自每 4 列之一的值。

重要提示:有时 4 列为空,那么 final 列也将为空

【问题讨论】:

  • 补充答案,有帮助吗?

标签: python-3.x pandas


【解决方案1】:
# find the max along the row, starting from second columns (skipping over ID)
df['final']=df.iloc[:,1:].max(axis=1).astype(int)
df[['id','final']]
   id   final
0   1    10
1   2    11
2   3     6
3   4     1

【讨论】:

    猜你喜欢
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多