2016-04-07 60 views
0

我真的不明白我在做什麼。我有兩個數據幀。一個有一個列標籤列表,另一個有一堆數據。我想用我的列標籤標記我的數據中的列。如何用另一個數據框重命名pandas dataframe列?

我的代碼:

airportLabels = pd.read_csv('airportsLabels.csv', header= None) 

airportData = pd.read_table('airports.dat', sep=",", header = None) 
df = DataFrame(airportData, columns = airportLabels) 

當我做到這一點,所有的數據變成「南」,並且只有一列了。我很困惑。

回答

0

我想你需要添加參數nrowsread_csv,如果你需要只讀列,刪除header= None,因爲csv第一行是列名,然後在read_tablecolumnsDataFrameairportLabels使用參數names

import pandas as pd 
import io 

temp=u"""col1,col2,col3 
1,5,4 
7,8,5""" 
#after testing replace io.StringIO(temp) to filename 
airportLabels = pd.read_csv(io.StringIO(temp), nrows=0) 
print airportLabels 
Empty DataFrame 
Columns: [col1, col2, col3] 
Index: [] 

temp=u""" 
a,d,f 
e,r,t""" 
#after testing replace io.StringIO(temp) to filename 
df = pd.read_table(io.StringIO(temp), sep=",", header = None, names=airportLabels.columns) 
print df 
    col1 col2 col3 
0 a d f 
1 e r t 
+0

謝謝,但那似乎不起作用。現在有數據(不再有NaN),但列標籤現在是「0,1,2 ...等) – pythonnoob

+0

請給我時間,我測試它 – jezrael

+0

非常感謝!刪除」headers = none 「從標籤文件似乎解決它。 – pythonnoob

相關問題