新聞中心
python在DataFrame數(shù)據(jù)中添加列的方法:

超過十余年行業(yè)經(jīng)驗,技術領先,服務至上的經(jīng)營模式,全靠網(wǎng)絡和口碑獲得客戶,為自己降低成本,也就是為客戶降低成本。到目前業(yè)務范圍包括了:成都網(wǎng)站設計、成都做網(wǎng)站,成都網(wǎng)站推廣,成都網(wǎng)站優(yōu)化,整體網(wǎng)絡托管,微信小程序,微信開發(fā),重慶APP開發(fā),同時也可以讓客戶的網(wǎng)站和網(wǎng)絡營銷和我們一樣獲得訂單和生意!
1、使用concat方法在數(shù)據(jù)中添加列
concat方法相當于數(shù)據(jù)庫中的全連接(union all),它不僅可以指定連接的方式(outer join或inner join)還可以指定按照某個軸進行連接。
示例:
import pandas as pd
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()函數(shù)添加的結果如下:
a b 0 4.459256 8.225418 1 0.043276 6.307400 2 6.997162 9.313393 3 4.754832 9.260378 4 8.661904 9.767977 a b c 0 4.459256 8.225418 NaN 1 0.043276 6.307400 NaN 2 6.997162 9.313393 NaN 3 4.754832 9.260378 NaN 4 8.661904 9.767977 NaN
2、使用reindex()方法在指定位置添加列
import pandas as pd
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()方法可以添加一列或多列數(shù)據(jù),并且可以指定列的位置,也可以對原先存在的列進行重排。方法中的columns屬性控制著列的位置,c是添加的一列,其位于a和b前面,這說明c列是新數(shù)據(jù)框的第一列,fill_value屬性指定的是添加一列的值,其結果如下:
a b 0 4.459256 8.225418 1 0.043276 6.307400 2 6.997162 9.313393 3 4.754832 9.260378 4 8.661904 9.767977 c a b 0 1 4.459256 8.225418 1 1 0.043276 6.307400 2 1 6.997162 9.313393 3 1 4.754832 9.260378 4 1 8.661904 9.767977
當前題目:創(chuàng)新互聯(lián)Python教程:python數(shù)據(jù)怎么添加列?
本文路徑:http://www.5511xx.com/article/dpppjed.html


咨詢
建站咨詢
