如何用另一个数据帧重命名pandas dataframe列?

时间:2016-04-07 15:15:40

标签: pandas

我真的不明白我在做什么。我有两个数据帧。一个有列标签列表,另一个有一堆数据。我想用我的列标签标记数据中的列。

我的代码:

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

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

当我这样做时,所有数据变成" NaN"并且只有一列了。我真的很困惑。

1 个答案:

答案 0 :(得分:0)

我认为您需要将参数nrows添加到read_csv,如果您需要只读列,请删除header= None,因为csv的第一行是列名,然后使用来自names columns DataFrame的{​​{3}}中的参数airportLabels

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