I have a dataframe:
entry_df <- data.frame(date = seq(as.Date("2018/01/01"), as.Date("2018/01/07"),
"days"),diff = c(1,0,-1 , 0,0 ,1,-1))
entry_df
date diff
1 2018-01-01 1
2 2018-01-02 0
3 2018-01-03 -1
4 2018-01-04 0
5 2018-01-05 0
6 2018-01-06 1
7 2018-01-07 -1
I want to rbind
the rows that are betwen 1
and -1
in a dataframe
and push it on a list
.
Steps:
2018-01-01
is equal 1
so it will be my first element of my dataframe
2018-01-02
is equal to 0
so I need to rbind it to the first dataframe
2018-01-03
is equal to -1
so I need to rbind it to the first dataframe and that will constitue the first element of the list
2018-01-04
and 2018-01-05
is equal to 0
so i don't do anything ...
2018-01-06
is equal to 1
so i create a dataframe at it will be the first element of it. 2018-01-07
is equal to -1
so i will rbind to the dataframe and that will constitute the second element of the list
Expected output is something like this
output_list[[1]] <- data.frame(date = seq(as.Date("2018/01/01"),
as.Date("2018/01/03"), "days"))
output_list[[2]] <- data.frame(date = seq(as.Date("2018/01/06"),
as.Date("2018/01/07"), "days"))
output_list
[[1]]
date
1 2018-01-01
2 2018-01-02
3 2018-01-03
[[2]]
date
1 2018-01-06
2 2018-01-07
We can use the iloc() function to slice DataFrames into smaller DataFrames. The iloc() function allows us to access elements based on the index of rows and columns. Using this function, we can split a DataFrame based on rows or columns.
Slicing a DataFrame in Pandas includes the following steps:Ensure Python is installed (or install ActivePython) Import a dataset. Create a DataFrame. Slice the DataFrame.
In the above example, the data frame 'df' is split into 2 parts 'df1' and 'df2' on the basis of values of column 'Weight'. Method 2: Using Dataframe. groupby(). This method is used to split the data into groups based on some criteria.
Assuming that the number of 1's and -1s are the same, get the index of row with ==
and which
, then loop over the indexes using Map
and subset the 1st column of 'entry_df'
Map(function(i, j) entry_df[i:j, 1, drop = FALSE],
which(entry_df$diff == 1), which(entry_df$diff == -1))
#[[1]]
# date
#1 2018-01-01
#2 2018-01-02
#3 2018-01-03
#[[2]]
# date
#6 2018-01-06
#7 2018-01-07
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With