【问题标题】:From DataFrame, to list. Python Pandas从 DataFrame 到列表。蟒蛇熊猫
【发布时间】:2020-12-11 18:06:48
【问题描述】:

我有一个在不同列中有一些空值的数据框。我想从该数据框“数据”创建一个列表,在该列表中我只能看到具有非空值的列。我还创建了一个missing_row_counts 列表,其中包括每列具有的空值数量。 这是我的代码。

def non_zeros(series):
    """Returns a list of the index values in series for which
    the value is greater than 0.
    """ 
    for i in missing_row_counts:
      nonzero_row = i > 0 #need to fix 
    return nonzero_row

上面的代码运行,但是当我调用它时: missing_cols = non_zeros(missing_row_counts) missing_cols 它返回 True 我期望列的所有列都具有值的列表

【问题讨论】:

标签: python


【解决方案1】:
non_zeros = list(series[series > 0].index.values)

【讨论】:

  • 是的,谢谢拉格斯。有效。我对数据进行了交叉核对并进行了检查。干杯
【解决方案2】:

你可以像这样使用矢量化来做到这一点:

import pandas as pd
import numpy as np
data = pd.DataFrame({"a": [1,2], "b": [3, np.NaN]})
non_nan_columns = data.columns[data.isnull().sum(axis=1) == 0]

请在您的下一个问题中提供一个工作示例;)

【讨论】:

    【解决方案3】:

    nonzero_row = i > 0 将始终返回 True 或 False,因为您正在进行比较。

    但是,更简单的方法是发送电子邮件至df.isna().any(),示例如下:

    df = pd.DataFrame({'a': [1,2,3], 'b':[np.nan, 2,3], 'c': [1,2,3]})
    col_has_na = df.isna().any() #this checks if `any` column of df has na
    print(col_has_na)
    a    False
    b     True
    c    False
    #In above output `a` and `c` does not have na, hence False, whereas its True for `b`
    
    #Fiter out and get index of columns which have False value
        print(col_has_na[~col_has_na].index.tolist())
        ['a', 'c']
    

    【讨论】:

      猜你喜欢
      • 2016-10-16
      • 2021-11-09
      • 1970-01-01
      • 2021-02-18
      • 2022-01-09
      • 2015-03-23
      • 2019-05-02
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多