从聚合via.loc添加新列返回NaN

2024-10-02 10:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解为什么我的代码不能按预期工作

我有一个数据结构: Screenshot to dataframe (对不起,我没有足够高的声誉来发布图片)

我按如下方式求和,得到testBytes

aggregation = {'testBytes' : ['sum']}
tests_DL_groupped = tests_DL_short.groupby(['measDay','_p_live','_p_compositeId','Latitude','Longitude','testType']).agg(aggregation).reset_index()

现在实际的问题是为什么这段代码不能按预期工作NaN

tests_DL_groupped.loc[:,'testMBytes'] = tests_DL_groupped['testBytes']/1000/1000

a not working

虽然此工作正常

tests_DL_groupped['testMBytes'] = tests_DL_groupped['testBytes']/1000/1000

a working

哪种方式应该是最好的方式

多谢各位


Tags: to代码数据结构dataframe方式图片testsworking
1条回答
网友
1楼 · 发布于 2024-10-02 10:24:16

列中存在问题MultiIndex

解决办法是改变:

aggregation = {'testBytes' : ['sum']}

致:

aggregation = {'testBytes' : 'sum'}

为了避免它

或使用^{}

cols = ['measDay','_p_live','_p_compositeId','Latitude','Longitude','testType']
tests_DL_groupped = tests_DL_short.groupby(cols)['testBytes'].sum().reset_index()

tests_DL_groupped = tests_DL_short.groupby(cols, as_index=False)['testBytes'].sum()

相关问题 更多 >

    热门问题