python - 从现有数据帧的每一行创建新数据帧的 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 函数并使用动态创建的变量来实现我自己的解决方案,但我想知道解决问题的推荐、最简单和优雅的方法是什么。
解决方案
好的,我认为我为这个问题找到的解决方案是所有建议中最好的一个,所以我将在这里分享:
首先,我们将使用“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}
这是我能找到的最直接的解决方案。请问您对以上有什么意见吗?(如果有更好的解决方案,我会更改接受的答案。)
推荐阅读
- android - Android约束布局定位1项在其他下方
- ssis - 找不到成员 0x80020003 SSIS
- sql - 从 SQL Server 中的列中提取值
- python - 修改所有页面的 paginate_by 的值
- excel - 最后一行返回 1 - 不正确的值
- javascript - UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“包含”
- javascript - Storybook jest 插件不显示结果
- javascript - 在没有 express 的情况下在节点 js 中获取请求正文的替代方法
- mysql - mysql 变体到来自 sql 查询的列
- reactjs - 为什么这个 react-spring 动画在动画期间会改变它的 margin-top?