Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slicing of data into separate Dataframe

Tags:

dataframe

r

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:

  1. 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

  2. 2018-01-04 and 2018-01-05 is equal to 0 so i don't do anything ...

  3. 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
like image 572
patrick Avatar asked Feb 13 '18 08:02

patrick


People also ask

How do you split a data frame into two?

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.

Can we do slicing in DataFrame?

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.

How do you split a DataFrame into two parts based on condition?

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.


1 Answers

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
like image 139
akrun Avatar answered Oct 28 '22 07:10

akrun