全部版块 我的主页
论坛 经济学论坛 三区 宏观经济学
1453 0
2022-01-23
pandas 案例[color=rgba(0, 0, 0, 0.298039)]以下文章来源于萝卜大杂烩[color=rgba(0, 0, 0, 0.298039)] [color=rgba(0, 0, 0, 0.298039)],作者周萝卜
[color=rgba(0, 0, 0, 0.298039)]1如何使用列表和字典创建 Series使用列表创建 Seriesimport pandas as pd

ser1 = pd.Series([1.5, 2.5, 3, 4.5, 5.0, 6])
print(ser1)

Output:

0    1.5
1    2.5
2    3.0
3    4.5
4    5.0
5    6.0
dtype: float64
使用 name 参数创建 Seriesimport pandas as pd

ser2 = pd.Series(["India", "Canada", "Germany"], name="Countries")
print(ser2)

Output:

0      India
1     Canada
2    Germany
Name: Countries, dtype: object
使用简写的列表创建 Seriesimport pandas as pd

ser3 = pd.Series(["A"]*4)
print(ser3)

Output:

0    A
1    A
2    A
3    A
dtype: object
使用字典创建 Seriesimport pandas as pd

ser4 = pd.Series({"India": "New Delhi",
                  "Japan": "Tokyo",
                  "UK": "London"})
print(ser4)

Output:

India    New Delhi
Japan        Tokyo
UK          London
dtype: object
2如何使用 Numpy 函数创建 Seriesimport pandas as pd
import numpy as np

ser1 = pd.Series(np.linspace(1, 10, 5))
print(ser1)

ser2 = pd.Series(np.random.normal(size=5))
print(ser2)

Output:

0     1.00
1     3.25
2     5.50
3     7.75
4    10.00
dtype: float64
0   -1.694452
1   -1.570006
2    1.713794
3    0.338292
4    0.803511
dtype: float64
3如何获取 Series 的索引和值
import pandas as pd
import numpy as np

ser1 = pd.Series({"India": "New Delhi",
                  "Japan": "Tokyo",
                  "UK": "London"})

print(ser1.values)
print(ser1.index)

print("\n")

ser2 = pd.Series(np.random.normal(size=5))
print(ser2.index)
print(ser2.values)

Output:

['New Delhi' 'Tokyo' 'London']
Index(['India', 'Japan', 'UK'], dtype='object')


RangeIndex(start=0, stop=5, step=1)
[ 0.66265478 -0.72222211  0.3608642   1.40955436  1.3096732 ]
4如何在创建 Series 时指定索引import pandas as pd

values = ["India", "Canada", "Australia",
          "Japan", "Germany", "France"]

code = ["IND", "CAN", "AUS", "JAP", "GER", "FRA"]

ser1 = pd.Series(values, index=code)

print(ser1)

Output:

IND        India
CAN       Canada
AUS    Australia
JAP        Japan
GER      Germany
FRA       France
dtype: object
5如何获取 Series 的大小和形状import pandas as pd

values = ["India", "Canada", "Australia",
          "Japan", "Germany", "France"]

code = ["IND", "CAN", "AUS", "JAP", "GER", "FRA"]

ser1 = pd.Series(values, index=code)

print(len(ser1))

print(ser1.shape)

print(ser1.size)

Output:

6
(6,)
6


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群