python - .reset_index 之后的 fillna() 用于创建 DataFrame
问题描述
我为某些用户提供了 3 个带有呼叫、消息和互联网数据的 dfs。我使用 groupby 来查找每个用户每月使用的呼叫数(或消息数,或 GB),然后用于.reset_index
将 MultiIndexes 转换为 DataFrames。通过进一步分析,我注意到对于某些用户 id,存在 NaN 值,因为几个月来,一些活跃用户没有拨打任何电话、发送任何消息或使用任何数据。为了解决我尝试使用.fillna()
但它不起作用的问题,所以当我为 total_calls 提取具有已知 NaN 值的特定 user_id 时,它会打印一个空数据帧。
我试过了:
calls_mins_per_month.fillna({'duration':0}, inplace=True)
calls_mins_per_month['duration'] = calls_mins_per_month['duration'].fillna(0)
calls_mins_per_month['duration'].fillna(0, inplace=True)
这是我为每个用户每月调用的 DataFrame 的代码:
#For each user, find the number of calls made and minutes used per month:
calls_mins_per_month = megaline_calls.groupby(['user_id', "call_month"]).agg({"call_id": len, "duration": "sum"})
calls_mins_per_month.rename(columns={'call_id':'total_calls'}, inplace=True)
calls_mins_per_month = calls_mins_per_month.reset_index()
#print(calls_mins_per_month['duration'].isna().count())
calls_mins_per_month.fillna({'duration':0}, inplace=True)
有人可以指出我做错了什么吗?
解决方案
您可以尝试一些操作:
使用 df.replace(' ','') 可能是一个空白空间,并且无法将 fillna() 识别为 'Nan' 值,或者检查 Nan 值是否实际上不是 'Nan' 字符串,如果是,则你可以做 df.replace('Nan', '')
希望你能解决它
推荐阅读
- java - Java:给定一个其值为数组的 HashMap,操作这些数组的值的最佳方法是什么?
- c++ - 使用 2D 动态分配数组通过 MPI_Gatherv 收集数据?
- clojure - 是否可以从输入文件中读取并将文本文件的每一行转换为字符串向量?
- oracle - 如何在包中使用编辑列(它显示编辑值)
- python - 如何解决此错误:矩阵大小不兼容:In[0]:[1,786432],In[1]:[784,512] [[{{node MatMul}}]]>
- sql - 按 somecolumn 分组以获得总值并按 somecolumn 以相反的顺序对值求和
- java - 通过记录器的 Java Spark 应用程序日志未显示在 EMR 日志中
- javascript - 为什么我的 JavaScript 数据库表是空的?
- c# - 如何通过在移动设备上触摸来更改对象属性 (UNITY) (2D)
- ios - 如何使用 AVFoundation (>1 min) 录制长视频?