python - 在数据框中找到最后一个值和相应的列名

标签 python pandas indexing

在下面的数据框中,我想找出每一行中的最后一个值,以及包含最后一个值的列名

df

 ID   c1   c4   c3    c2   c8   c7
 1     1    2    2    1    NaN  NaN
 2     1    2    1    NaN  NaN  NaN
 3     1    1    NaN  NaN  2     1

预期输出

 ID     Colname    lastValue
 1        c2         1
 2        c3         1
 3        c7         1

我的代码只能找到最后一个值

df['lastValue'] = df.ffill(axis = 1).iloc[:, -1]

我怎样才能找到 colname?

谢谢!

最佳答案

last_valid_index+lookup

s=df.apply(pd.Series.last_valid_index, 1)
df['Last']=df.lookup(s.index,s)
df['Col']=s
df
Out[49]: 
   ID  c1  c4   c3   c2   c8   c7  Last Col
0   1   1   2  2.0  1.0  NaN  NaN   1.0  c2
1   2   1   2  1.0  NaN  NaN  NaN   1.0  c3
2   3   1   1  NaN  NaN  2.0  1.0   1.0  c7

关于python - 在数据框中找到最后一个值和相应的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49198387/

相关文章:

python - 如何在 TemplateView 类旁边接收 GET/POST 值

python - 使用 Pandas,如何将行值拆分为单独的列,并使用它们的值?

hstore bool 属性的 PostgreSQL 索引

python - 处理 Tkinter 文本小部件索引系统。

javascript - 使用indexOf检索数组值

python - 如何从两个列表(其中一个是嵌套的)创建字典?

python - 有什么办法可以让这一小段代码变得更短吗? (Python)

python - 如果组中的任何一行包含特定值,则创建新列并分配值

python - 如何使用分组统计信息将列添加到数据框

python - 如何处理 colspan == '' 的 td 标签?