#DataFrame数据结构,很像二维表格数据结构,也是python中最常用的数据结构
import pandas as pd
import numpy as np
#创建DataFrame数据
#先给出一个字典data,我们用字典来创建
data={
"name":["唐浩","小王","老王","赵三","李四"],
"sex":["男","女","男","女","男"],
"year":[37,22,15,18,33],
"city":["成都","北京","上海","成都","深圳"]
}
# df1=pd.DataFrame(data)
# print(df1)
"""
name sex year city
0 唐浩 男 37 成都
1 小王 女 22 北京
2 老王 男 15 上海
3 赵三 女 18 成都
4 李四 男 33 深圳
"""
# df2=pd.DataFrame(data,columns=["name","year","sex","city"]) #指定列名顺序
# print(df2)
#指定列序与索引
# df3=pd.DataFrame(data,columns=["name","year","sex","city"],index=["a","b","c","d","e"]) #指定列名顺序
# print(df3)
#上面演示的是字典创建DataFrame数据
#下面从其它数据类型来创建DataFrame数据
#用numpy的矩阵数据来创建pd的DataFrame数据,不指定列的话,列名与索引一样,
# np1=np.arange(0,12).reshape(4,3)
# print(np1)
# df4=pd.DataFrame(np1)
# print(df4)
# df5=pd.DataFrame(np1,columns=["一","二","三"]) #指定列名
# print(df5)
#用pd的Series数据来创建DataFrame,也是可以的,不过只有一列数据,因Series是一维的
# objs1=pd.Series(["name","year","sex","city"])
# print(objs1)
# df6=pd.DataFrame(objs1)
# print(df6)
#通过列表元组来创建DataFrame数据,结果与pd.Series的结果一样,因都是一维数组
# ll=["namel","yearl","sexl","cityl"]
# tt=("namet","yeart","sext","cityt")
# df7l=pd.DataFrame(ll)
# df8t=pd.DataFrame(tt)
# print(df7l)
# print("_________")
# print(df8t)
#设置name属性,注:列可以通过df9["列名"]访问,也可通过df9.列名 访问与设置
# df9=pd.DataFrame(data)
# print(df9)
# df9.index.name="id"
# df9.columns.name="gogo"
# print("________________")
# print(df9)
# print(df9.values)
# print(df9.keys())
原文地址:https://www.cnblogs.com/yiyea/p/11441789.html