【问题标题】:In python how Print total number of columns that contain null values & also print the column names of null to a csv output file在 python 中,如何打印包含空值的列总数以及将空的列名打印到 csv 输出文件
【发布时间】:2019-06-09 17:11:41
【问题描述】:

得到一个包含几列的 csv 文件,并且数据包含特定列的空值。使用 pandas 数据框函数,如何将包含空值和空列名的列总数打印到输出 csv 文件?

输出.csv 2 # 列数 a栏 b栏

【问题讨论】:

  • 你能添加一个示例数据框和预期的输出吗?谢谢
  • 项目编号、城市、州、total_sales 预期输出到 csv 文件。 2 # 列数 Column a Column c
  • 不不不,你一定要检查这个是否有未来的问题:stackoverflow.com/questions/20109391/…

标签: python pandas dataframe


【解决方案1】:

我准备的测试数据如下:

np.random.seed(0)
df = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('ABCDEFGHIJ'))
df[df > 0.9] = pd.np.nan; df

要获取包含 NaN 值的列名,请运行:

nn = df.isnull().any()

对于我的测试数据,结果是:

A     True
B    False
C    False
D     True
E    False
F    False
G    False
H     True
I     True
J    False
dtype: bool

我们实际上对值为 True 的索引值感兴趣。 要获取它们,请运行:

nullCols = nn.index[nn].tolist()

结果是:

['A', 'D', 'H', 'I']

要获取此类列的数量,请运行:

len(nullCols)

结果是4

【讨论】:

    【解决方案2】:

    以下代码可帮助您实现上述目标:

        df=pd.DataFrame({'Name':["abc","def",None],'Age':[1,None,3],'Address':["rst","uvw","xyz"]})
    
        null_colname=df.columns[df.isnull().any()].tolist() #find columns which returns True for null testing and convert the column names to list
        null_colnum=len(null_colname)                       # take length of the above list
    
        p=str(null_colnum)+"# of columns:"                  # initialize string in the format of required output
        for i in range(0,null_colnum):                      #iterate over the list
            p=p+'Column-'+null_colname[i]+' '               # concatenate column names to the string
    
    
        text_file = open(filepath+"Output.csv", "w")        #export to csv
        text_file.write("%s" % p)
        text_file.close()
    

    【讨论】:

    • 谢谢瑞米尔。如何调整 output.csv 使其输出一行中的列数和每行中的列名。?
    • 根据我的理解,您希望第一行是列数,而相应的行是列名。您可以通过以下方式进行操作:codelist_col=list(null_colname) text_file = open(filepath+"Output.csv", "w") #export to csv text_file.write(p) text_file.write("\n" ) for col_name in list_col: text_file.write(col_name) text_file.write("\n") text_file.close() code 或者您可以将其转换为数据框 'code' df_final=pd.DataFrame() df_final[p] =list_col df_final.to_csv(filepath+"\\output.csv",index=False) code
    【解决方案3】:

    试试:

    pd.DataFrame({'Columns': a.columns[a.isnull().any()], 'Count':len([x for x in a.isnull().any().values if x == True])}).to_csv('myfilepath.csv')
    

    a 是您的数据框名称,将 any() 更改为 all() 是您要检查整个列是否为空。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多