簡體   English   中英

如何在 for 循環中的數據框中插入新列?

[英]How to insert a new column in a dataframe within a for loop?

超級新手 Python/Pandas 問題。

我正在嘗試讀取包含多個工作表的 Excel 工作簿文件夾,將列標題提取為列表,並將每個列表添加為 pandas DataFrame 中的新列。 這是我到目前為止的代碼:

import pandas as pd
import numpy as np

filepath = '/content/data.xlsx'

workbook = pd.read_excel(filepath, None, nrows=0)

variables_frame = []

for sheet_name, sheet in workbook.items():
  variables = sheet.columns
  variables_list = list(variables)
  variables_frame = pd.DataFrame.insert(sheet+1, sheet_name, [variables_list])
  print(variables_frame)

但是,當我嘗試運行它時,出現錯誤“TypeError: insert() missing 1 required positional argument: 'value'”。 任何想法為什么?

此外,如果這不是解決此問題的正確方法,我將不勝感激任何更一般的反饋。 謝謝!

問題是您直接從類中調用insert函數

class A:
    def insert(self, x):
        print(f'insert {x}')

# Right
A().insert(3)

# Wrong
A.insert(3)

你可能想要

variables_frame = pd.DataFrame()
for sheet_name, sheet in workbook.items():
  variables = sheet.columns
  variables_list = list(variables)
  variables_frame.insert(sheet+1, sheet_name, [variables_list])
  print(variables_frame)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM