Fit a longer np array into a shorter but wider panda dataframe

I have a data frame “p” and a np array “b” as follow

p=pd.DataFrame([["j","k","h"],[4,5,6],[7,8,9]])

j k h
4 5 6
7 8 9


b=np.array([["a",10],["b",20],["c",30],["d",40]])

a 10
b 20
c 30
d 40

I want to insert the np array to the dataframe and make become as follow

j  k   h
a  10  10 
b  20  20
c  30  30
d  40  40

Notice p is wider than b and b is longer than p

Basically:

  1. keep the first row of the p
  2. insert b into p from second row
  3. repeat second column of b to the rest of column of p

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

IIUC, you can use:

pd.concat([p.iloc[[0]],
           pd.DataFrame(np.hstack([b, b[:,[1]]]), columns=p.columns)],
          ignore_index=True)

output:

   0   1   2
0  j   k   h
1  a  10  10
2  b  20  20
3  c  30  30
4  d  40  40


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x