Pandas中 DataFrame的使用

读取行

DataFrame读取行可以通过以下两种索引

  • 行标签索引 df.loc["one"]
  • 行号索引 df.iloc[0]

行标签索引可以在创建DataFrame的时候指定,如

1
2
3
4
5
import pandas as pd
d=[[1,2,3,4],[5,6,7,8]]
index=["one","two"]
df=pd.DataFrame(d, index=index)
print df.loc["one"]

行号索引(index)可以通过df.index来查看

1
2
3
>>> df.index
RangeIndex(start=0, stop=18, step=1) # 0~17
>>> df.iloc[0] # 获取第一行

也可以全部都用df.ix[]

1
2
df.ix[3] # 读取第三行
df.ix["three"]

读取列

1
2
3
# 两个参数,第一个类似切片,指定要获取的行
# 第二个是一个list, 指定要获取的列名
df.ix[:, ["Stations"]]

列名可以通过df.columns获取

1
2
3
4
>>> df.columns
Index(['Station', 'To Tiu Keng Leng', 'To Kwun Tong', 'To Whampoa',
'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6'],
dtype='object')

DataFrame转成list

1
2
import numpy as np
l = np.array(df).tolist()

Reference