簡體   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

假設我有多個 pandas 數據幀,我想檢查它們的列數並創建一個 def function 這樣做,怎么樣? 已經自己嘗試過,但是當我使用以下代碼時,它會返回類型錯誤

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

循環遍歷數據幀並計算列數的代碼

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