【问题标题】:How to remove nan and .0 in pandas when importing lists from excel从excel导入列表时如何删除熊猫中的nan和.0
【发布时间】:2022-01-14 09:50:32
【问题描述】:

[我的 Excel 电子表格]

我的代码:

import pandas as pd

dictionary = pd.read_excel('dictionary.xlsx').to_dict('list')

model_name = input('model name ')

print(dictionary[model_name])

输入 = 模型 3 时的输出:

[11508589.0, 11508572.0, 11508541.0, nan, nan, nan, nan, nan]

期望的输出:

[11508589, 11508572, 11508541]

【问题讨论】:

  • [x for x in lst if pd.notna(x)]
  • 检查 pd.DataFrame.dropna() 的缺失值,处理逗号的字符串格式。或强制转换为 int。

标签: python pandas list dictionary nan


【解决方案1】:

在 pandas 中使用 dropna 方法:

print(dictionary[model_name].dropna())

【讨论】:

    【解决方案2】:

    Pandas 行的所有列都必须有值,NaN 表示没有值(无)。

    # ask for column
    mn = input('model name ') 
    # read dataframe, select column, drop NaN
    pd.read_excel('dictionary.xlsx')[mn].dropna()
    

    【讨论】:

      【解决方案3】:

      解决方案:

      df = pd.read_excel('dictionary.xlsx')
      dictionary = df.apply(lambda s: s.dropna().astype(int).tolist()).to_dict()
      

      【讨论】:

        猜你喜欢
        • 2013-12-12
        • 1970-01-01
        • 2018-12-18
        • 2021-07-01
        • 1970-01-01
        • 2015-08-12
        • 1970-01-01
        • 2020-08-23
        • 2021-11-12
        相关资源
        最近更新 更多