pandas创建数据表及数据读写

本文介绍如何使用 Python 的 Pandas 库进行数据处理,包括创建 DataFrame、填充缺失值及读写 Excel 文件等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.7897190.8217450.441262barFalseball
c-0.305278-2.4248531.876305barFalseball
e1.009320-0.820649-0.022101barTrueball
f0.490864-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.640581-0.532271barTrueball
dNaNNaNNaNNaNNaNNaN
e-0.2311921.7404890.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.640581-0.532271barTrueball
d0.000000NaNNaNNaNNaNNaN
e-0.2311921.7404890.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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值