Python數(shù)據(jù)分析與展示:DataFrame類型簡單操作-9
發(fā)布時間:2021-11-23 點擊數(shù):760
DataFrame類型
DataFrame類型由共用相同索引的一組列組成
DataFrame是一個表格型的數(shù)據(jù)類型,每列值類型可以不同
DataFrame既有行索引、也有列索引
index axis=0
axis=1 column
DataFrame常用于表達二維數(shù)據(jù),但可以表達多維數(shù)據(jù)
DataFrame類型可以由如下類型創(chuàng)建:
二維ndarray對象
由一維ndarray、列表、字典、元組或Series構(gòu)成的字典
Series類型
其他的DataFrame類型
DataFrame是二維帶“標簽”數(shù)組
DataFrame基本操作類似Series,依據(jù)行列索引
代碼示例
# -*- coding: utf-8 -*- # @File : dataframe_demo.py # @Date : 2018-05-20 import pandas as pd import numpy as np # DataFrame對象 # 從二維ndarray對象創(chuàng)建 自動行、列索引 df = pd.DataFrame(np.arange(10).reshape(2, 5)) print(df) """ 0 1 2 3 4 0 0 1 2 3 4 1 5 6 7 8 9 """ # 從一維ndarray對象字典創(chuàng)建 dt = { "one": pd.Series([1, 2, 3], index=["a", "b", "c"]), "two": pd.Series([5, 6, 7, 8], index=["a", "b", "c", "d"]) } df = pd.DataFrame(dt) print(dt) """ { 'one': a 1 b 2 c 3 dtype: int64, 'two': a 5 b 6 c 7 d 8 dtype: int64 } """ # 數(shù)據(jù)根據(jù)行列索引自動補齊 df = pd.DataFrame(dt, index=["a", "b", "c"], columns=["one", "two"]) print(df) """ one two a 1 5 b 2 6 c 3 7 """ # 從列表類型的字典創(chuàng)建 dt = { "one": [1, 2, 3, 4], "two": [5, 6, 7, 9] } df = pd.DataFrame(dt, index=["a", "b", "c", "d"]) print(df) """ one two a 1 5 b 2 6 c 3 7 d 4 9 """ # 獲取行索引 print(df.index) # Index(['a', 'b', 'c', 'd'], dtype='object') # 獲取列索引 print(df.columns) # Index(['one', 'two'], dtype='object') # 獲取值 print(df.values) """ [[1 5] [2 6] [3 7] [4 9]] """ # 獲取列 print(df["one"]) """ a 1 b 2 c 3 d 4 Name: one, dtype: int64 """ #獲取行 print(df.ix["a"]) """ one 1 two 5 Name: a, dtype: int64 """ # 獲取某單元格的值 print(df["one"]["a"]) # 1