使用前先下载pandas包,pip install pandas
SeriesPandas Series 类似表格中的一个列(column),类似于一维数组,可以保存任何数据类型。
import pandas as pa;
print(pa.__version__)
#定义字典
mydataset ={
'size':["Goole","Runoob","wiki"],
'number':[1,2,3]
}
#将字典转换为DataFrame,才能处理
mydf=pa.DataFrame(mydataset)
print(mydf)
a=[1,2,3]
mysr=pa.Series(a,name="number")
print(mysr)
print(mysr[2])
#制定series的索引值
a = ["Goole","Runoob","Wiki"]
myvar = pa.Series(a,index=["x","y","z"])
print(myvar['y'])
s = {1 : "Goole",2:"Runoob",3:"Wiki"}
myvar2=pa.Series(s)
print(myvar2[3])
s = {1 : "Goole",2:"Runoob",3:"Wiki"}
myvar3=pa.Series(s,index=[1,2])
print(myvar3)
#定义二维列表
data =[['Goole',10],['Runoob',12],['Wiki',13]]
#将列表转换为DataFrame
mydf=pa.DataFrame(data,columns=['name','age'])
print(mydf)
#将字典转换为DataFrame
data = {'Site':['Google','Runoob','Wiki'],'Age':[10,12,13]}
mydf1=pa.DataFrame(data)
print(mydf1)
data = [{'a':1,'b':2},{'a':5,'b':10,'c':20}]
print(pa.DataFrame(data))
data = {'cala':[213,21,1321],'dura':[10,12,13]}
print(pa.DataFrame(data).loc[0])
print(pa.DataFrame(data).loc[[0,1]])
data = {'cala':[213,21,1321],'dura':[10,12,13]}
print(pa.DataFrame(data,index=['row1','row2','row3']))
csv
import pandas as pd;
# df=pd.read_csv('',encoding='GBK')
# print(df)
# df.to_csv('',encoding='utf-8')
nme=["Google","Runoob","Taobao","Wiki"]
st=["www.google.com","www.runoob.com","www.taobao.com","www.wikipedia.org"]
ag=[90,40,80,98]
# 将列表转变为字典
dic={'name':nme,'site':st,'ag':ag}
#将字典转变为DataFrame
df=pd.DataFrame(dic)
#将DataFrame保存至csv文件\
df.to_csv('./dic.csv',encoding='utf-8')
#读取csv文件到DataFrame
df=pd.read_csv('./dic.csv')
#打印前几行
print(df.head(2))
#打印后几行
print(df.tail(2))
# 返回基本信息
print(df.info())
json
import pandas as pd
# 读取json文件到dataframe
json=pd.read_json('./sites.json')
print(json)
#
# 将数据保存为json文件
data=[
{
"id": "A001",
"name": "菜鸟教程",
"url": "www.runoob.com",
"likes": 61
},
{
"id": "A002",
"name": "Google",
"url": "www.google.com",
"likes": 124
},
{
"id": "A003",
"name": "淘宝",
"url": "www.taobao.com",
"likes": 45
}
]
df=pd.DataFrame(data)
df.to_json('data.json')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)