【问题标题】:fillna() after .reset_index was used to create DataFrame.reset_index 之后的 fillna() 用于创建 DataFrame
【发布时间】:2021-07-05 20:19:48
【问题描述】:

我有 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)

有人能指出我做错了什么吗?

【问题讨论】:

  • 请编辑帖子以包含您的数据的外观、您的代码显示的内容以及它的作用
  • 在 fillna 之前显示输出 print(calls_mins_per_month['duration'].isna().count())

标签: python pandas dataframe missing-data


【解决方案1】:

您可以尝试一些操作:

使用 df.replace(' ','') 可能是一个空白空间,并且无法将 fillna() 识别为 'Nan' 值 或检查 Nan 值是否实际上不是 'Nan' 字符串,如果是,则可以执行 df.replace('Nan', '')

希望你能解决

【讨论】:

    猜你喜欢
    • 2017-02-08
    • 2019-01-12
    • 2017-01-29
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2016-11-24
    相关资源
    最近更新 更多