在特定点对 DataFrame 进行切片并绘制每个切片 [英] Slice DataFrame at specific points and plot each slice

查看:74
本文介绍了在特定点对 DataFrame 进行切片并绘制每个切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,Pythone 你能帮我吗?我有一个看起来像这样的数据框.

I am new to programming and Pythone could you help me? I have a data frame which look like this.

d = {'time': [4, 10, 15, 6, 0, 20, 40, 11, 9, 12, 11, 25], 
     'value': [0, 0, 0, 50, 100, 0, 0, 70, 100, 0,100, 20]}    
df = pd.DataFrame(data=d)

我想在 value == 100 时对数据进行切片,然后在一个figer 中绘制所有切片.所以我的问题是如何按照描述对数据进行切片或切割?以及为了绘图而保存切片的最佳结构是什么?.

I want to slice the data whenever value == 100 and then plot all slices in a figer. So my questions are how to slice or cut the data as described? and what's the best structure to save slices in order to plot?.

注意 1:值列没有我可以使用的频率,它在 0 到 100 之间变化,其中时间是任意的.

Note 1: value column has no frequency that I can use and it varies from 0 to 100 where time is arbitrary.

注意 2:我已经尝试过这个解决方案,但我得到了相同的表

Note 2: I already tried this solution but I get the same table

decreased_value = df[df['value'] <= 100][['time', 'value']].reset_index(drop=True)

如何根据条件将数据框中的一列切片为多个系列

提前致谢!

推荐答案

这是处理我的第一个答案的一种更简单的方法(感谢@aneroid 的建议).

Here's a simpler way of handling my first answer (thanks to @aneroid for the suggestion).

获取 value==100 的索引并添加 +1 使它们位于每个切片的底部:

Get the indices where value==100 and add +1 so that these land at the bottom of each slice:

indices = df.index[df['value'] == 100] + 1

然后使用 numpy.split(感谢 this 这个方法的答案)来制作数据帧列表:

Then use numpy.split (thanks to this answer for that method) to make a list of dataframes:

df_list = np.split(df, indices)

然后对 for 循环中的每个切片进行绘图:

Then do your plotting for each slice in a for loop:

for df in df_list:
     --- plot based on df here ---

详细/从头开始的方法:

您可以像这样获取value==100 的索引:

You can get the indices for where value==100 like this:

indices = df.index[df.value==100]

然后添加最小和最大索引,以免遗漏 df 的开头和结尾:

Then add the smallest and largest indices in order to not leave out the beginning and end of the df:

indices = indices.insert(0,0).to_list()
indices.append(df.index[-1]+1)

然后通过一个while循环来切割数据帧并将每个切片放入一个数据帧列表中:

Then cycle through a while loop to cut up the dataframe and put each slice into a list of dataframes:

i = 0
df_list = []
while i+1 < len(indices):
    df_list.append(df.iloc[indices[i]:indices[i+1]])
    i += 1

这篇关于在特定点对 DataFrame 进行切片并绘制每个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆