【问题标题】:python progrom to find the null values in row and return the column namepython程序在行中查找空值并返回列名
【发布时间】:2019-03-17 15:17:19
【问题描述】:

我想根据现有列AFNaN 值的位置创建一个新列null_columns

A   B    C    D    E   F    null columns
0   1   NaN   3    5   4       ['C']
0  NaN  NaN  NaN   6   4   ['B','C','D']
2   3    5    4   NaN  5       ['E'] 

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您应该编辑您的问题,以便每个人都清楚,例如你使用了什么格式,你试图得到什么输出等等。

    实际上,这是一个有趣的问题。我假设你有以上熊猫数据框格式的数据。添加更多与您的问题相关的标签也很重要。

    无论如何,我找不到比下面的代码更有效的方法。希望对你有帮助:

    nul_index = []
    for i in df:
        nul_index.append(df[df[i].isnull()].index.tolist())
    

    这将为您提供按列排列的空值行索引列表。在上述情况下:[[],[1],[0,1],[1],[2],[]]

    从该列表中,我们希望将 [['C'],['B','C','D'],['E']] 之类的内容分配给我们的新列。

    new_col = []
    for i in range(len(df)):
        new_col.append([df.columns[x] for x in range(len(nul_index)) if i in nul_index[x]])
    df['null_column'] = new_col
    

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 2017-02-21
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      相关资源
      最近更新 更多