天天看點

Pandas 如何建立 DataFrame如何建立 Series?如何建立 DataFrame?

– Start

如何建立 Series?

我們已經知道了什麼是 Series,在使用 Series 之前,我們得知道如何建立 Series。

import pandas as pd

# 自動建立 index
my_data = [10, 20, 30]
s = pd.Series(data=my_data)
print(s)

# 指定 index
my_index = ['UK', 'US', 'CN']
s = pd.Series(data=my_data, index=my_index)
print(s)

# 根據字典建立 Series
my_dict = {'UK':10, 'US':20, 'CN':30}
s = pd.Series(data=my_dict)
print(s)

# 同字典,根據索引通路
print(f"data of index CN is {s['UK']}")

           

如何建立 DataFrame?

我們已經知道了什麼是 DataFrame,在使用 DataFrame 之前,我們得知道如何建立 DataFrame。

import numpy as np
import pandas as pd

pd.set_option('display.max_columns', 100)
pd.set_option('display.max_rows', 100)
pd.set_option('display.width', 1000)


# 通過 numpy 數組建立 DataFrame,預設行标簽和列标簽
data = np.random.randn(6, 4)
df = pd.DataFrame(data)
print(df)


# 指定行标簽和列标簽
row_index = pd.date_range('20180101', periods=6)
column_label = list('ABCD')
df = pd.DataFrame(data, index=row_index, columns=column_label)
print(df)


# 通過字典建立 DataFrame
data = {'A':['A0', 'A1', 'A2'],
        'B':['B0', 'B1', 'B2'],
        'C': ['C0', 'C1', 'C2'],}
df = pd.DataFrame(data)
df = pd.DataFrame(data, index=['L0', 'L1', 'L2'])
print(df)


# http://www.csindex.com.cn/zh-CN/downloads/indices?lb=%E5%85%A8%E9%83%A8&xl=1
# 通過讀取 Excel 檔案建立 DataFrame
df = pd.read_excel("index300.xls", sheet_name="Price Return Index")
df = pd.read_excel("index300.xls", sheet_name="Price Return Index", index_col=0)
print(df)
           

通常我們都是通過讀取檔案建立 DataFrame,DataFrame 提供了下面的 read_* 方法可以從不同的資料源建立 DataFrame。

read_csv
read_json
read_html
read_clipboard
read_excel
read_hdf
read_feather
read_parquet
read_msgpack
read_stata
read_sas
read_pickle
read_sql
read_gbq

           

– 更多參見:Pandas 精萃

– 聲 明:轉載請注明出處

– Last Updated on 2018-11-10

– Written by ShangBo on 2018-10-29

– End

繼續閱讀