[英]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.