更新 pandas groupby().last() 的列值 [英] update column value of pandas groupby().last()

查看:35
本文介绍了更新 pandas groupby().last() 的列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定的数据框:

dfd = pd.DataFrame({'A': [1, 1, 2,2,3,3],
                    'B': [4, 5, 6,7,8,9],
                    'C':['a','b','c','c','d','e']
                   })

我可以通过使用

dfd.groupby('A').last()['C']

但是,我想将 C 值更新为 np.nan.我不知道该怎么做.方法如:

However, I want to update the C values to np.nan. I don't know how to do that. Method such as:

def replace(df):
    df['C']=np.nan
    return replace

dfd.groupby('A').last().apply(lambda dfd: replace(dfd))

不起作用.

我想要这样的结果:

dfd_result= pd.DataFrame({'A': [1, 1, 2,2,3,3],
                    'B': [4, 5, 6,7,8,9],
                    'C':['a',np.nan,'c',np.nan,'d',np.nan]
                   })

推荐答案

IIUIC,你需要loc.使用 tail

IIUIC, you need loc. Get the index of last values using tail

In [1145]: dfd.loc[dfd.groupby('A')['C'].tail(1).index, 'C'] = np.nan

In [1146]: dfd
Out[1146]:
   A  B    C
0  1  4    a
1  1  5  NaN
2  2  6    c
3  2  7  NaN
4  3  8    d
5  3  9  NaN

dfd.loc[dfd.groupby('A').tail(1).index, 'C'] = np.nan 也应该没问题.

这篇关于更新 pandas groupby().last() 的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆