簡體   English   中英

將 pandas 系列值添加到 pandas Z6A8064B5DF479455507DZ553

[英]add pandas series values to new dataframe column at end of pandas dataframe

我有一個 dataframe ,其值如下:

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

以及具有如下值的系列:

0 | 9
1 | 6
2 | 8

如何將系列值添加到 dataframe 中的新列中以獲得此值?

    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

在此先感謝您,我是編碼新手,不知道如何使用 concat 或合並 pandas 函數來使其正常工作。

df 是您的主要 dataframe 和您的系列,您可以這樣做:

#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

例子:

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

Output 運行上述代碼后:

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

你可以試試這個

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)

希望這能解決您的問題。

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

另一個系列的一個想法,其索引的長度為 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM