您好,欢迎来到爱玩科技网。
搜索
您的当前位置:首页pandas创建数据表及数据读写

pandas创建数据表及数据读写

来源:爱玩科技网

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],
                  columns=['one', 'two', 'three'])#创建一个数据表格
df['four'] = 'bar'#加入新的一列
df['five'] = df['one'] > 0#加入新的一列,通过判断数据大小加入bool型列
df['six'] = 'ball'

df

 onetwothreefourfivesix
a-0.77190.8217450.441262barFalseball
c-0.305278-2.4248531.876305barFalseball
e1.009320-0.8209-0.022101barTrueball
f0.4908-0.196651-1.365382barTrueball
h-1.342600-0.0543220.196686barFalseball

df2 = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])#增加新的行并填充为NaN

df2

 onetwothreefourfivesix
a0.9494880.851231-0.654962barTrueball
bNaNNaNNaNNaNNaNNaN
c0.785113-0.0581-0.532271barTrueball
dNaNNaNNaNNaNNaNNaN
e-0.2311921.74040.421804barFalseball
f-0.4741950.2555730.057918barFalseball
gNaNNaNNaNNaNNaNNaN
h1.3406230.793281-0.114751barTrueball
df2['one']=df2['one'].fillna(0)#按列填充

df2

 onetwothreefourfivesix
a0.9494880.851231-0.654962barTrueball
b0.000000NaNNaNNaNNaNNaN
c0.785113-0.0581-0.532271barTrueball
d0.000000NaNNaNNaNNaNNaN
e-0.2311921.74040.421804barFalseball
f-0.4741950.2555730.057918barFalseball
g0.000000NaNNaNNaNNaNNaN
h1.3406230.793281-0.114751barTrueball

读取Excel数据

#读取excel数据
import pandas as pd
FileReadPath = r"D:\AI\Others\test.xlsx"
df = pd.read_excel(FileReadPath)
df.head()

写Excel数据

#把数据写入Excel
import pandas as pd
data = {'country':['aaa','btb','ccc'],  
       'population':[10,12,14]}  
df = pd.DataFrame(data)#构建DataFrame结构  
FileWritePath = r"D:\AI\Others\test1.xlsx"
writer = pd.ExcelWriter(FileWritePath)
df.to_excel(writer,'Sheet1')
writer.save()

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- aiwanbo.com 版权所有 赣ICP备2024042808号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务