如何添加新列作为第一个?

时间:2015-09-15 16:25:25

标签: python pandas dataframe

我编写了以下代码,为pandas DataFrame添加了一个新列:

validnew=validation[features]
validnew['const'] = pd.Series([0 for x in range(len(validation.index))], index=validation.index)

print validnew.head()

       season  holiday  workingday  weather   temp   atemp  humidity  \
10341       4        0           1        2  12.30  15.150        61   
10342       4        0           1        2  13.12  16.665        57   
10343       4        0           1        1  13.94  17.425        53   
10344       4        0           1        1  13.94  16.665        53   
10345       4        0           1        1  15.58  19.695        43   

       windspeed  year  month  weekday  hour  const  
10341    11.0014  2012     11        4     7      0  
10342     8.9981  2012     11        4     8      0  
10343     7.0015  2012     11        4     9      0  
10344    12.9980  2012     11        4    10      0  
10345    15.0013  2012     11        4    11      0 

如何将列'const'添加为第一列? 此外,上面给出的代码给出了这个警告:

C:/Tests/lreg.py:119: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

1 个答案:

答案 0 :(得分:0)

如果您想要一个全0的列,请使用insert并使用broadcasting

validnew.insert(0, 'const', 0) 
相关问题