python - 按行拆分数据帧并在python中生成数据帧列表
问题描述
我有一个数据框:
data = {'Timestep' : [0,1,2,0,1,2,3,0,1],
'Price' : [5,7,3,5,7,10,8,4,8],
'Time Remaining' : [10.0,10.0,10.0,15.0,15.0,15.0,15.0,12.0,12.0]}
df = pd.DataFrame(data, columns = ['Timestep','Price','Time Remaining'])
我想将数据帧转换为一个包含多个数据帧的列表,其中每个时间步长序列 (0-2,0-3,0-1) 是一个数据帧。此外,我希望时间步长成为每个数据集中的索引。最后应该是这样的:
我有一个包含数千行和不规则序列的数据框,所以我想我必须遍历这些行。
有谁知道我该如何解决这个问题?
解决方案
据我了解-每当您Timestep
达到 0时,您都需要一个新的 DataFrame-
这是你可以尝试的
#This will give you the location of all zeros [0, 3, 7]
zero_indices = list(df.loc[df.Timestep == 0].index)
#We append the number of rows to this to get the last dataframe [0, 3, 7, 9]
zero_indices.append(len(df))
#Then we get the ranges - tuples of consecutive entries in the above list [(0, 3), (3, 7), (7, 9)]
zero_ranges = [(zero_indices[i], zero_indices[i+1]) for i in range(len(zero_indices) - 1)]
#And then we extract the dataframes into a list
list_of_dfs = [df.loc[x[0]:x[1] - 1].copy(deep=True) for x in zero_ranges]
推荐阅读
- r - 如何增加绘图的高度以在 r 中闪亮的 flexdashboard 中占据整个高度空间?
- python - 如何使用 Pandas 在 Python 中将两个字符串拆分为不同的列?
- python - 使用“预测”函数进行逻辑回归时出错
- java - 如何使用 Firebase 中的用户令牌向特定用户发送通知?
- reactjs - React Native 和底部选项卡导航,弓在屏幕之间导航
- javascript - 当我将表单发布到特定 api 时如何获得响应
- c++ - if 语句的错误结果
- python - Tensorflow Serving docker:基本路径 /models/model 下没有可服务的 colbert 创始人的版本
- javascript - 如何从 JavaScript 调用 Kotlin 函数
- ios - NativeScript Angular 应用程序在播放声音 iOS 后崩溃