Slice Dataframe At Specific Points And Plot Each Slice
Solution 1:
EDIT:
Here's a simpler way of handling my first answer (thanks to @aneroid for the suggestion).
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
Then use numpy.split
(thanks to this answer for that method) to make a list of dataframes:
df_list = np.split(df, indices)
Then do your plotting for each slice in a for loop:
fordfin df_list:
--- plot based on df here ---
VERBOSE / FROM SCRATCH METHOD:
You can get the indices for where value==100
like this:
indices = df.index[df.value==100]
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)
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
Solution 2:
I already solved the problem using for loop
, which can be used to slice and plot at the same time without using np.split
function, as well as maintain the data structure.
Thanks to the previous answer by @k_n_c, it helps me improve it.
slices = df.index[df['score'] == 100]
slices = slices + 1
slices = np.insert(slices, 0,0, axis=0)
slices = np.append(slices,df.index[-1]+1)
prev_ind = 0
for ind in slices:
temp = df.iloc[prev_ind:ind,:]
plt.plot(temp.time, temp.score)
prev_ind = ind
plt.show()
Post a Comment for "Slice Dataframe At Specific Points And Plot Each Slice"