python在DataFrame数据中添加列的方法:
1、使用concat方法在数据中添加列
concat方法相当于数据库中的全连接(union all),它不仅可以指定连接的方式(outer join或inner join)还可以指定按照某个轴进行连接。
示例:
importpandasaspd feature=pd.read_csv("C://Users//Machenike//Desktop//xzw//lr_train_data.txt",delimiter="\t",header=None,usecols=[0,1]) feature.columns=["a","b"] print(feature.head()) feature=pd.concat([feature,pd.DataFrame(columns=list('c'))]) print(feature.head())
利用concat()函数添加的结果如下:
ab 04.4592568.225418 10.0432766.307400 26.9971629.313393 34.7548329.260378 48.6619049.767977 abc 04.4592568.225418NaN 10.0432766.307400NaN 26.9971629.313393NaN 34.7548329.260378NaN 48.6619049.767977NaN
2、使用reindex()方法在指定位置添加列
importpandasaspd feature=pd.read_csv("C://Users//Machenike//Desktop//xzw//lr_train_data.txt",delimiter="\t",header=None,usecols=[0,1]) feature.columns=["a","b"] print(feature.head()) feature=feature.reindex(columns=list('cab'),fill_value=1) print(feature.head())
reindex()方法可以添加一列或多列数据,并且可以指定列的位置,也可以对原先存在的列进行重排。方法中的columns属性控制着列的位置,c是添加的一列,其位于a和b前面,这说明c列是新数据框的第一列,fill_value属性指定的是添加一列的值,其结果如下:
ab 04.4592568.225418 10.0432766.307400 26.9971629.313393 34.7548329.260378 48.6619049.767977 cab 014.4592568.225418 110.0432766.307400 216.9971629.313393 314.7548329.260378 418.6619049.767977原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容