简体   繁体   中英

add pandas series values to new dataframe column at end of pandas dataframe

I have a dataframe with values like this:

    A | B | C 
0 | 1 | 2 | 3
1 | 1 | 4 | 2
2 | 3 | 3 | 1
3 | 5 | 2 | 4
4 | 3 | 1 | 3

And a series with values like this:

0 | 9
1 | 6
2 | 8

How do i add the series values to a new column in the dataframe to get this?

    A | B | C | E
0 | 1 | 2 | 3 | NaN
1 | 1 | 4 | 2 | NaN
2 | 3 | 3 | 1 | 9
3 | 5 | 2 | 4 | 6
4 | 3 | 1 | 3 | 8

Thank you in advance, im new to coding and cant figure out how to use the concat or merge pandas functions to get this to work.

With df being your main dataframe and ser your series, you can do this:

#these 2 lines, in order to confirm that both indexes start from 0
df.reset_index(drop=True, inplace=True)
ser.reset_index(drop=True, inplace=True)

ser.index=ser.index+max(df.index)-max(ser.index)

df['new']=ser

Example:

df = pd.DataFrame(np.random.randint(0,10,[10,2]),columns=['a', 'b'])
ser = pd.Series({0:100, 1:200, 3:300})

Output after running the above code:

a  b    new
0  7  8    NaN
1  8  0    NaN
2  9  0    NaN
3  9  3    NaN
4  0  7    NaN
5  7  0    NaN
6  9  7    NaN
7  4  3  100.0
8  9  9  200.0
9  4  3  300.0

You can try this

one = pd.DataFrame(np.random.randint(0,10,(5,3)),columns=list('ABC'))
two = pd.Series([1,2,3],index=[2,3,4])

pd.concat((one,two),axis=1)

Hopefully this will solve your problem.

df = pd.DataFrame([[1,2,3,4], [3,4,5,6], [3,6, 7, 8], [3,4,5,6], [3,4,5,6]])
se = pd.Series([3,5,6])

df["new"] = np.nan #creating new column & filling it with nan
l = se.shape[0]#getting length of your series
df['new'][-l:] = se #adding the series to the end of new column

One idea with another Series with index by length of Series s :

s = pd.Series([9,6,8])
df['E'] = pd.Series(s.to_numpy(), df.index[-len(s):])
print (df)
   A  B  C    E
0  1  2  3  NaN
1  1  4  2  NaN
2  3  3  1  9.0
3  5  2  4  6.0
4  3  1  3  8.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM