前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Pandas 如何创建 DataFrame

Pandas 如何创建 DataFrame

作者头像
用户7886150
修改2020-12-28 11:07:46
修改2020-12-28 11:07:46
1.6K0
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: 创建一个Pandas 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

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档