DataFrame:表格型的数据结构,含有一个组有序的列,每列可以是不同的值的类型。DataFrame既有行索引也有列索引,可以看做是由Series组成的字典。(我自己是将看成关系数据库的表格形式)
DataFrame的构造函数:
pandas.DataFrame( data, index, columns, dtype, copy) data:一组数据(ndarray、series, map, lists, dict 等类型)。 index:索引值,或者可以称为行标签。 columns:列标签,默认为 RangeIndex (0, 1, 2, …, n) 。 dtype:数据类型。 copy:拷贝数据,默认为 False。
使用列表创建(加column的index)
data = [['Google', 10], ['Edge', 2], ["Firefox"]] t1 = pd.DataFrame(data, columns=['Browser', 'score']) print(t1) #缺失的数据自动填充为Nan Browser score 0 Google 10.0 1 Edge 2.0 2 Firefox NaN
使用ndarray创建
data = {'Browser':['Google', 'Edge', 'Firefox'], 'score':[10, 2, np.nan]}
t3 = pd.DataFrame(data)
print(t3)
Browser score
0 Google 10.0
1 Edge 2.0
2 Firefox NaN
使用字典创建
data = [{'a': 1, 'b': 100}, {'a': 2, 'b': 3, 'c': 60}]
t2 = pd.DataFrame(data)
print(t2) # 注意:没有对应的数据则为NaN
a b c
0 1 100 NaN
1 2 3 60.0
访问数据
按index访问数据:
print(t2.loc[1]) # 返回一个Series数据类型 Browser Edge score 2.0 Name: 1, dtype: object print(t2.loc[[1]]) # 返回DataFrame数据类型 Browser score 1 Edge 2.0
按column访问数据:
print(t3['Browser']) 0 Google 1 Edge 2 Firefox
找某一个值:
print(t3.loc[0, 'Browser']) # loc[index, column] Google



