首页 > 解决方案 > 从现有数据帧的每一行创建新数据帧的 Pythonic 方法

问题描述

请推荐一种从现有数据框的每一行创建新数据框的pythonic方法。

该建议必须考虑到现有数据帧的行数是随机的,因此提供的解决方案必须考虑到这一点。(由于下面的示例,原始数据框包含 3 行,但是原始数据框中的实际行数将是随机的。)原始数据框的列将保持不变。

原始数据框:

import pandas as pd
from numpy.random import randn
 
df = pd.DataFrame(randn(3,3), columns=['column 1', 'column 2', 'column 3'], index = ['row 1', 'row 2', 'row 3'])
print(df)

输出:

       column 1  column 2  column 3
row 1  0.972855 -0.179018  0.177614
row 2 -2.146628 -1.639054 -0.708013
row 3 -1.295298 -0.313462 -0.229140

解决方案实施后的所需输出(创建如下三个新数据框,保留原始列):

数据框1:

   column 1  column 2  column 3
row 1  0.972855 -0.179018  0.177614

数据框2:

    column 1  column 2  column 3
row 2 -2.146628 -1.639054 -0.708013

数据框 3:

    column 1  column 2  column 3
row 3 -2.146628 -1.639054 -0.708013

我还想保留处理创建的新数据框和操作其中数据的能力。

我试图通过使用 .iterrows 函数并使用动态创建的变量来实现我自己的解决方案,但我想知道解决问题的推荐、最简单和优雅的方法是什么。

标签: pythondataframe

解决方案


好的,我认为我为这个问题找到的解决方案是所有建议中最好的一个,所以我将在这里分享:

首先,我们将使用“for”循环和“.itertuples()”函数遍历原始数据库的行。在循环中,“.itertuples()”函数返回的数据用于构建一个新的 pandas 数据库,然后将其存储在字典中。存储每个新创建的数据库的字典键来自“.itertuples”函数返回的第一个元素。

import pandas as pd
from numpy.random import randn
 
df = pd.DataFrame(randn(3,3), columns=['column 1', 'column 2', 'column 3'], index = ['row 1', 'row 2', 'row 3'])

row = df.itertuples()

my_dict = {}

for row in df.itertuples():
    my_dict[row[0]] = pd.DataFrame([list(row)[1:]], columns=['column 1', 'column 2', 'column 3'],
                                   index = [row[0]])

print(my_dict)

输出:

{'row 1':        column 1  column 2  column 3
row 1  2.083922  1.513993  0.861644, 'row 2':        column 1  column 2  column 3
row 2  0.988185 -0.685701  0.252542, 'row 3':        column 1  column 2  column 3
row 3 -0.526314 -1.481147 -1.789547}

这是我能找到的最直接的解决方案。请问您对以上有什么意见吗?(如果有更好的解决方案,我会更改接受的答案。)


推荐阅读