簡體   English   中英

如何在 pandas 的 for 循環迭代中創建多個數據幀?

[英]How to create multiple dataframes within for loop iteration in pandas?

I need to create a function in pandas that takes a single dataframe as input and returns multiple dataframes as output based on a specific condition. (請檢查以下示例以了解情況)。 我很難弄清楚如何。 我需要一些專家關於編碼的建議。

示例 1:

輸入= dataframe 100 列

輸出= 具有前 10% 列(第 1 到 10 列)的 dataframe1,具有第二個 10% 列(第 11 到 20 列)的 dataframe2,依此類推,直到最后 10% 列(第 91 到 100 列)。

示例 2:

輸入= dataframe 109 列

輸出= dataframe1 包含前 10% 的列(四舍五入)(第 1 到 11 列),dataframe2 包含第二個 10% 列(第 12 到 23 列),依此類推,直到最后 10% 列(第 109 列)

這是我正在嘗試開發的邏輯:

  1. 從原始 dataframe 中的列總數中找到 10% 的值作為“n”
  2. 從原始 dataframe 中選擇前“n”列。
  3. 將它們添加到新的 dataframe
  4. 將它們從原始 dataframe
  5. 檢查原始dataframe中的總列數是否大於'n'
  6. 如果否 -> 重復步驟 2 到步驟 5。
  7. 如果是 -> 將所有剩余的列添加到最后創建的 dataframe。

我嘗試了以下代碼,但它是錯誤的 在下面的代碼中,我試圖根據百分比拆分獲得受尊重的列號,稍后我計划使用這些數字使用 iloc function 拆分 dataframe。

def split_column_numbers(total_columns, percentage_split):
    list1 = []
    number = round((total_columns * (percentage_split/100)))
    list1.append([0,number])
    for i in range(number):
        last_num = list1[-1][-1]
        if (last_num < total_columns):
            if((total_columns-last_num) > number):
                list1.append([last_num+1, last_num+number])
            else:
                list1.append([last_num+1, total_columns])
    return list1
split_column_numbers(101, 10)

任何人都可以幫助我了解這個邏輯是否正確以及如何實現這一點?

如果你將你的框架直接傳遞給 function,它應該會讓你更容易確定以后要抓取哪些列。 我們可以使用math.ceil進行四舍五入,並使用itertools.zip_longest拆分為我們的子組。

from itertools import zip_longest
from math import ceil


def split_columns(frame, percentage_split):
    cols = frame.columns
    grp_size = ceil(len(cols) * percentage_split/100)
    return [[c for c in grp if c] for grp in zip_longest(*(iter(cols),) * grp_size)]

例如,如果我們設置一個虛擬框架如下:

from string import ascii_lowercase

import pandas as pd

tmp = pd.DataFrame(columns=list(ascii_lowercase))

然后,如果我們執行split_columns(tmp, 10)我們得到:

[['a', 'b', 'c'],
 ['d', 'e', 'f'],
 ['g', 'h', 'i'],
 ['j', 'k', 'l'],
 ['m', 'n', 'o'],
 ['p', 'q', 'r'],
 ['s', 't', 'u'],
 ['v', 'w', 'x'],
 ['y', 'z']]

如果我們做split_columns(tmp, 30)我們得到:

[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
 ['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'],
 ['q', 'r', 's', 't', 'u', 'v', 'w', 'x'],
 ['y', 'z']]

如果我們想使用這些列選擇來創建新框架,您可以使用字典理解來執行此操作,然后enumerate

frames = {i: tmp[cols] for i, cols in enumerate(split_columns(tmp, 30))}

這給了我們一個字典,其中鍵是整數(第一組列對應於 0,第二組對應於 1 等),值是從 dataframe 中選擇的列。

暫無
暫無

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

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