猿问

考虑到中间的空白列,如何计算列数?

如果df某些列之间有空格,我如何计算列数?我df基于 XLS 文件创建,它有这样的问题。空白列的数量未知,但从不超过 20。


df =


col1   col2   col3        col4

112    ret    56          xx

34     wet    45          yy

如何计算列数: * 得到 4 列(不考虑空白列) * 得到 5 列(考虑空白列)。


该方法应该适用于非空白列之间的任意数量的空白列。


更新:


pandas DataFramedf的创建方式如下:


f_path = "C://test/myfile_with_blank_columns.xls"

df = pd.read_excel(open(f_path,'rb'), sheet_name='goal')

数据示例(某些文件不包含标题):


0   0   24.1    23.9    24.4    24.3                            2.880136

0   0   24.1    23.9    24.4    24.3                            2.878689

0   0   24.1    23.9    24.4    24.3                            2.875072

0   0   24.1    23.9    24.4    24.3                            2.883029


www说
浏览 238回答 2
2回答

森栏

这取决于空白列的格式。例如,考虑它们是空字符串的情况:df = pd.DataFrame({'A': [1,2,3],                    '' : ['','',''],                    'B': [1,2,3]})选项1:您可以尝试计算空列的数量:df_columns = list(df.columns)num_cols = len(df_columns) - df_columns.count('')print(num_cols)# returns 2选项 2:另一种选择是使用.isidentifier()string 方法,这将更加健壮,因为它将空字符串和空格都检测为空白列。但是,它会过滤掉任何带有空格的列!因此,仅当您的非空列具有格式良好的列名时,这再次起作用。num_cols = np.sum([col.isidentifier() for col in df.columns])print(num_cols)# prints 2

慕运维8079593

这是简单的解决方案dff = pd.read_excel('D:/test.xlsx',sheet_name='goal',header=None, na_values=' ') #This will convert blank values to NaNdff    0  1     2     3     4     5   6   7   8         90  0  0  24.1  23.9  24.4  24.3 NaN NaN NaN  2.8801361  0  0  24.1  23.9  24.4  24.3 NaN NaN NaN  2.8786892  0  0  24.1  23.9  24.4  24.3 NaN NaN NaN  2.8750723  0  0  24.1  23.9  24.4  24.3 NaN NaN NaN  2.883029获取列(不考虑空白列)col = list(dff.drop(dff.loc[:,list((100*(dff.isnull().sum()/len(dff.index))==100))].columns, 1).columns.values)print(col)# [0, 1, 2, 3, 4, 5, 9]print(len(col))# 7获取列(考虑空白列)all_col = dff.columns.tolist()print(all_col)# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print(len(all_col))# 10注意:您可以创建没有空白列的单独数据框df1 = dff[col]df1   0  1     2     3     4     5         90  0  0  24.1  23.9  24.4  24.3  2.8801361  0  0  24.1  23.9  24.4  24.3  2.8786892  0  0  24.1  23.9  24.4  24.3  2.8750723  0  0  24.1  23.9  24.4  24.3  2.883029
随时随地看视频慕课网APP

相关分类

Python
我要回答