-
杨__羊羊
使用numpy.hstack向数组添加一个值:1ddf1 = pd.DataFrame({'a': range(6)})arr1 = np.arange(15).reshape(5,3)print (arr1)[[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]]df1['aaa'] = np.hstack((np.nan, arr1[:,0]))print (df1) a aaa0 0 NaN1 1 0.02 2 3.03 3 6.04 4 9.05 5 12.0如果可能,另一个想法是使用具有索引的构造函数:DataFrameSeriesdf1.indexdf1 = pd.DataFrame({'a': range(6)}, index=list('abcdef'))arr1 = np.arange(15).reshape(5,3)print (arr1)[[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11] [12 13 14]]dif = df1.shape[0] - arr1.shape[0]df1['aaa'] = pd.Series(arr1[:,0], index=df1.index[dif:])print (df1) a aaaa 0 NaNb 1 0.0c 2 3.0d 3 6.0e 4 9.0f 5 12.0最后位置:dif = df1.shape[0] - arr1.shape[0]df1['aaa'] = pd.Series(arr1[:,0], index=df1.index[:-dif])print (df1) a aaaa 0 0.0b 1 3.0c 2 6.0d 3 9.0e 4 12.0f 5 NaN编辑:arr1 = np.arange(15).reshape(5,3)df1 = pd.DataFrame({'a': range(6)})如果选择只得到带有形状的数组,那么就有必要 numpy.hstack:01d(6,)a = np.hstack((np.nan, arr1[:,0]))print (a)[nan 0. 3. 6. 9. 12.]print (a.shape)(6,)df1['aaa'] = a如果通过获取具有形状的尺寸的数组来选择,则可以使用numpy.vstack:[0]2dMxN(6,1)a1 = np.vstack((np.nan, arr1[:,[0]]))print (a1)[[nan] [ 0.] [ 3.] [ 6.] [ 9.] [12.]]print (a1.shape)(6, 1)df1['aaa1'] = a1print (df1) a aaa aaa10 0 NaN NaN1 1 0.0 0.02 2 3.0 3.03 3 6.0 6.04 4 9.0 9.05 5 12.0 12.0
-
弑天下
虽然我可以看到其他几个答案,但没有一个真正解决了手头的问题。直观地说,你的方法是可以的;您正在列数组上垂直堆叠。nandf1['aaa'] = np.vstack((np.nan, arr1[:,0]))它应该工作,但它没有。这里的小问题是搜索列维度。 具有形状 ;它没有第二个维度。简单地重塑它将使工作正常。vstackarr1[:,0](1412, )(1412,1)vstackdf1['aaa'] = np.vstack((np.nan, arr1[:,0].reshape(-1,1)))
-
四季花海
你可以这样做,这里有结果。添加列,第一行是 NaN:df['aaa'] = pd.Series(ar1[:,0])ea = np.empty(df.shape[1]).fill(np.nan)df.loc[-1] = eadf.index = df.index + 1df = df.reset_index(drop=True).sort_values(by=['aaa'], na_position='first')这是您的数据框架:c1 c2 c30 1 2 31 10 20 30下面是数组:[[ 5 55] [ 50 550]]结果是这样的: c1 c2 c3 aaa2 NaN NaN NaN NaN0 1.0 2.0 3.0 5.01 10.0 20.0 30.0 50.0
-
POPMUISE
您可以使用 np.附加df1['aaa'] = np.append(np.nan, arr1[:,0])