How to slice rows from two pandas dataframes then merge them with some other value

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to slice rows from two pandas dataframes then merge them with some other value



I got two pandas dataframes and two indexes, and one datetime variable. What I would like to do is:



slice the dataframes with the indexes, then I got two rows.



combine the two rows to one row.



add the variable to the row.



then I can get new indexes and datetime values to form more rows, and assemble the rows to a new dataframe.



Example:



df1:


A B
0 0 10
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
6 6 16
7 7 17
8 8 18
9 9 19



df2:


C D
0 10 110
1 11 111
2 12 112
3 13 113
4 14 114
5 15 115
6 16 116
7 17 117
8 18 118
9 19 119



index: 3, 5, datetime: datetime.datetime(2018, 8, 10, 16, 53, 52, 760014)


datetime.datetime(2018, 8, 10, 16, 53, 52, 760014)



Output:


A B C D time
0 3 13 15 115 20180810-16:53:52:760014
... # More rows when there's more indexes and datetimes





what's the use of df2 in this?
– krishna
Aug 10 at 7:02





Hi krishna, the columns C and D are extracted from df2 by the index 5. it is a bit misleading, I'll edit the example
– Kevin Fang
Aug 10 at 7:04





1 Answer
1



You can try :


index = [3,5]
data = np.r_[df1.iloc[index[0]].values,df2.iloc[index[1]].values]
df = pd.DataFrame([data],columns = list('ABCD'))
dt = datetime.datetime(2018, 8, 10, 16, 53, 52, 760014)
df['date'] = dt



Output:


A B C D date
0 3 13 15 115 2018-08-10 16:53:52.760014






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard