简体   繁体   English

how to define a function that gets the number of columns in a pandas dataframe that takes the dataframe as the function's parameter

[英]how to define a function that gets the number of columns in a pandas dataframe that takes the dataframe as the function's parameter

say I got multiple pandas dataframes and I want to check their number of columns and create a def function that does that, how?假设我有多个 pandas 数据帧,我想检查它们的列数并创建一个 def function 这样做,怎么样? Already tried on my own but when I the following code it returns a type error已经自己尝试过,但是当我使用以下代码时,它会返回类型错误

import pandas as pd def load_csv(filename): filename = pd.read_csv(filename) return filename def columns_count(f): f = load_csv(f) columns = f.shape[1] return columns

Code to loop through dataframes and count number of columns循环遍历数据帧并计算列数的代码

def count_num_cols(df): return len(df.columns) # or df.shape[1] list_of_paths = ["C://Users//file.txt", ] for a_path in list_of_paths: df = pd.read_csv(a_path) print(count_num_cols(df.shape[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM