pandas读取csv,并进行Series取值操作

这篇博客介绍了如何使用Python的pandas库读取CSV文件,并展示了如何获取DataFrame中Series的一列、索引值、设置索引、获取内容以及进行切片操作。示例代码详细解释了每个步骤,适合初学者掌握数据处理基本技巧。

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

代码示例:

#读取CSV
import pandas as pd

df1 = pd.read_csv('test.csv')
print(df1)
'''
打印:
   userId  score  age
0       1     45   18
1       2     65   19
2       3     58   17
3       4     92   16
4       5     78   18
'''

#获取一列,即Series数据获取
series1 = df1['score']
print(series1)
'''
打印:
0    45
1    65
2    58
3    92
4    78
Name: score, dtype: int64
'''

#获取索引值
print(series1.index)    #打印:RangeIndex(start=0, stop=5, step=1)
print(series1.index.tolist())    #打印:[0, 1, 2, 3, 4]
#设置索引值
series1.index = list('abcde')
print(series1)
'''
打印:
a    45
b    65
c    58
d    92
e    78
Name: score, dtype: int64
'''
# 获取内容,series[索引值]  | series[位置值]
print('索引下标',series1['d'])    #打印:索引下标 92
print('位置下标',series1[3])    #打印:位置下标 92
#获取多个值
print(series1[['a','d']])
'''
打印:
a    45
d    92
Name: score, dtype: int64
'''
print(series1[[0,3]])
'''
打印:
a    45
d    92
Name: score, dtype: int64
'''
#Series切片
print(series1['a':'d'])     # 如果使用索引下标,左右都闭合
'''
打印:
a    45
b    65
c    58
d    92
Name: score, dtype: int64
'''
print(series1[0:4])    #如果使用位置下标,左闭右开
'''
打印:
a    45
b    65
c    58
d    92
Name: score, dtype: int64
'''

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值