Skip to main content
 首页 » 编程设计

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

2024年11月24日7think

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

df = 
 
col1   col2   col3        col4 
112    ret    56          xx 
34     wet    45          yy 

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

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

更新:

pandas DataFrame df 创建如下:

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 

请您参考如下方法:

这取决于空白列的格式。例如,考虑它们是空字符串的情况:

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