本文共 1628 字,大约阅读时间需要 5 分钟。
– Start
我们已经知道了什么是 Series,在使用 Series 之前,我们得知道如何创建 Series。
import pandas as pd# 自动创建 indexmy_data = [10, 20, 30]s = pd.Series(data=my_data)print(s)# 指定 indexmy_index = ['UK', 'US', 'CN']s = pd.Series(data=my_data, index=my_index)print(s)# 根据字典创建 Seriesmy_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。
import numpy as npimport pandas as pdpd.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)# 通过字典创建 DataFramedata = {'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 文件创建 DataFramedf = 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_csvread_jsonread_htmlread_clipboardread_excelread_hdfread_featherread_parquetread_msgpackread_stataread_sasread_pickleread_sqlread_gbq
– 更多参见:
– 声 明:转载请注明出处 – Last Updated on 2018-11-10 – Written by ShangBo on 2018-10-29 – End