簡體   English   中英

從 DataFrame 到列表。 Python Pandas

[英]From DataFrame, to list. Python Pandas

我有一個 dataframe 在不同的列中有一些 null 值。 我想從該 dataframe '數據' 創建一個列表,其中我只能看到具有非 null 值的列。 我還創建了一個 missing_row_counts 列表,其中包括每列具有的 null 值的數量。 這是我擁有的代碼。

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 我期望列的所有列都有值

non_zeros = list(series[series > 0].index.values)

你可以用這樣的矢量化來做到這一點:

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]

請在您的下一個問題中提供一個工作示例;)

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']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM