python数据怎么添加列?
发布时间:2026-01-05 22:26:23

在DataFrame数据中添加python的方法:
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
更多Python知识请关注Python自学网
下一篇 python序列解包是什么意思?
