Python Pandas中的Series(创建、replace、map、append)

Series

Series是dataframe中的基本数据结构,也可以认为是一维的dataframe。所以series中的操作也可以在dataframe中使用。

1. 创建Series

  • 可以传入列表或者是字典来创建 Series。如果传入的是列表,默认索引为 [0,1,2,…] 。
  • 如果传入的是字符串类型的数据,Series 返回的dtype是object;
  • 如果传入的是数字类型的数据,Series 返回的dtype是int64
>>> food = {'one':'apple','two':'egg','three':'watermelon'}
>>> s1 = pd.Series(food)
>>> s1
one           apple
two             egg
three    watermelon
dtype: object

>>> s2 = pd.Series([30,40,50])
>>> s2
0    30
1    40
2    50
dtype: int64

2. replace

replace不改变原series。

>>> s2.replace(40,0)
0    30
1     0
2    50
dtype: int64
>>> s2
0    30
1    40
2    50
dtype: int64

如果待修改的值不存在则忽略,不会报错。

>>> s2.replace([30,0],[np.nan,np.nan])
0     NaN
1    40.0
2    50.0
dtype: float64

3. map

映射。

替换数据项。

  • 输入可以是字典。key为要替换的数据项,value为替换后的数据项。没有出现在字典里的项原本的值会被抹去,记为Nan。
  • 输入也可以是Series对象,index相当于字典的key,对应的值相当于字典的value。
  • map同样不改变原数组,保留修改结果需要赋值给新变量。
>>> update = {'apple':'pineapple','egg':'pen'}
>>> s1.map(update)
one      pineapple
two            pen
three          NaN
dtype: object
应用函数

在map中输入一个函数,分别对series中的格个值进行该操作。

  • na_action参数置为’ignore’表示不对Nan值执行输入函数的操作。
# example1
>>> s2 = s1.map(update)
>>> s2.map('I have a {}'.format, na_action='ignore')
one      I have a pineapple
two            I have a pen
three                   NaN
dtype: object

# example2
>>> s3 = pd.Series([1,2,3])
>>> s3.map(lambda x: x+10)
0    11
1    12
2    13
dtype: int64

4. append (ndarray没有这个方法)

操作和list中类似,但是有区别:

  • series中有索引,所以如果不指定,拼接部分会从0开始重新索引
  • append不改变原series,要保留结果需要赋值给新变量。(list中是在原列表操作,返回值为append对象)
>> s2.append(pd.Series([70,80,90]))
0    30
1    40
2    50
0    70
1    80
2    90
dtype: int64
>>> s2
0    30
1    40
2    50
dtype: int64

用字典指定索引:

>>> s2.append(pd.Series({3:70,4:80,5:90}))
0    30
1    40
2    50
3    70
4    80
5    90
dtype: int64

用Series中的index参数指定:

>>> s2.append(pd.Series([70,80,90],index=[3,4,5]))
0    30
1    40
2    50
3    70
4    80
5    90
dtype: int64

用append函数的ignore_index参数,True表示忽略两个series原始索引。

>>> s2.append(pd.Series([70,80,90]),ignore_index=True)
0    30
1    40
2    50
3    70
4    80
5    90
dtype: int64

先记录这么多,之后想起来再补充~

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值