DataFrame類型
DataFrame類型由共用相同索引的一組列組成
DataFrame是一個表格型的資料類型,每列值類型可以不同
DataFrame既有行索引、也有列索引
index axis=0
axis=1 column
DataFrame常用于表達二維資料,但可以表達多元資料
DataFrame類型可以由如下類型建立:
二維ndarray對象
由一維ndarray、清單、字典、元組或Series構成的字典
Series類型
其他的DataFrame類型
DataFrame是二維帶“标簽”數組
DataFrame基本操作類似Series,依據行列索引
代碼示例
# -*- coding: utf-8 -*-
# @File : dataframe_demo.py
# @Date : 2018-05-20
import pandas as pd
import numpy as np
# DataFrame對象
# 從二維ndarray對象建立 自動行、列索引
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對象字典建立
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
}
"""
# 資料根據行列索引自動補齊
df = pd.DataFrame(dt, index=["a", "b", "c"], columns=["one", "two"])
print(df)
"""
one two
a 1 5
b 2 6
c 3 7
"""
# 從清單類型的字典建立
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