TOPIC

磷光与烟火逆流

一个敲代码的程序猿

Pandas 操作复习、技巧、示例

Pandas

Series

# 创建Series实例
import pandas as pd
a = [1,2,3]
myvar = pd.Series(a)
print(myvar)
0    1
1    2
2    3
dtype: int64

# 指定index
b = ["Google", "Runoob", "Wiki"]
my_Series = pd.Series(b,index=["x","y","z"])

print(my_Series)
x    Google
y    Runoob
z      Wiki
dtype: object

print(my_Series["y"])
Runoob

# 使用dict创建Series
sites = {1: "Google", 2: "Runoob", 3: "Wiki"}
myvar = pd.Series(sites)
print(myvar)
1    Google
2    Runoob
3      Wiki
dtype: object

# 使用dict创建并且指定index和name
sites = {1: "Google", 2: "Runoob", 3: "Wiki"}
myvar = pd.Series(sites, index = [1, 2], name="RUNOOB-Series-TEST" )
print(myvar)
1    Google
2    Runoob
Name: RUNOOB-Series-TEST, dtype: object

# 如果指定的index比原数据要少,则创建的Series数据以index为准
myvar = pd.Series(sites, index = [1, 2])
print(myvar)
1    Google
2    Runoob
dtype: object

DataFrame

构造方法:

pandas.DataFrame( data, index, columns, dtype, copy)

参数说明:

  • data:一组数据(ndarray、series, map, lists, dict 等类型)。
  • index:索引值,或者可以称为行标签。
  • columns:列标签,默认为 RangeIndex (0, 1, 2, …, n) 。
  • dtype:数据类型。
  • copy:拷贝数据,默认为 False。

创建DataFrame实例

# 使用列表创建
import pandas as pd
data = [['Google',10],['Runoob',12],['Wiki',13]]
df = pd.DataFrame(data, columns=["Site","age"],dtype=float)
print(df)

# 使用ndarrays创建
data = {'Site':['Google', 'Runoob', 'Wiki'], 'Age':[10, 12, 13]}
df = pd.DataFrame(data)
print(df)

# 使用dict创建
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print (df)
# 结果
   a   b     c
0  1   2   NaN
1  5  10  20.0

DataFrame行

import pandas as pd

data = {
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}

# 数据载入到 DataFrame 对象
df = pd.DataFrame(data)

# 返回第一行
print(df.loc[0])
print(df[0:1])
# 返回第二行
print(df.loc[1])
print(df[1:2])

# 行切片
print(df[:])
  

loc 和iloc

# loc 取行和列 取得是对应的行--index  列--columns
df.loc[行(index名),列(columns名)]
# 切片
df.loc[index1:index4,columns1:columns4]

# iloc 取的是第几行和第几列
df.iloc[行号(第几行),列号(第几列)]
# 切片
df.iloc[行1:行3,列1:列4]

DateFrame指定列保留小数位

df = pd.DataFrame({"A":[1.123,2.4561,3.4848643246,4.74964346464,5.123445], "B":[9.1456,8.15458,7.428874,6.45674614,0.12]})
# 整个Dataframe
df.round(2)
df.applymap(lambda x: '%.2f' % x)
# 指定不同列 保留不同小数位
df.round({"A":2,"B":3})
# 针对某一列 保留小数 转换成字符串
df['A'].map(lambda x: "%.2f" % x)

DateFrame修改指定的index或者是colmuns

df = pd.DataFrame({"A":[1.123,2.4561,3.4848643246,4.74964346464,5.123445], "B":[9.1456,8.15458,7.428874,6.45674614,0.12]})
df = df.rename(index={0:'a'}, columns = {'A':'a','B':'b'})

DateFrame进行数据筛选

df = pd.DataFrame({"A":[1.123,2.4561,3.4848643246,4.74964346464,5.123445], "B":['9.1456','8.15458','7.428874','6.45674614','0.12']})
# 数值比较
df[df["A"]>3] # > < = != 等

# 列中包含5的
df[df['B'].str.contains('5')]
# 列中不包含5的
df[~df['B'].str.contains('5')]

# in 筛选
df[~df['B'].isin(['7.428874','6.45674614','0.12'])]

DataFrame to_dict

>>> df = pd.DataFrame({'col1': [1, 2],
...                    'col2': [0.5, 0.75]},
...                   index=['row1', 'row2'])
>>> df
      col1  col2
row1     1  0.50
row2     2  0.75
>>> df.to_dict()
{'col1': {'row1': 1, 'row2': 2}, 'col2': {'row1': 0.5, 'row2': 0.75}}

You can specify the return orientation.

>>> df.to_dict('series')
{'col1': row1    1
         row2    2
Name: col1, dtype: int64,
'col2': row1    0.50
        row2    0.75
Name: col2, dtype: float64}

>>> df.to_dict('split')
{'index': ['row1', 'row2'], 'columns': ['col1', 'col2'],
 'data': [[1, 0.5], [2, 0.75]]}

>>> df.to_dict('records')
[{'col1': 1, 'col2': 0.5}, {'col1': 2, 'col2': 0.75}]

>>> df.to_dict('index')
{'row1': {'col1': 1, 'col2': 0.5}, 'row2': {'col1': 2, 'col2': 0.75}}

You can also specify the mapping type.

>>> from collections import OrderedDict, defaultdict
>>> df.to_dict(into=OrderedDict)
OrderedDict([('col1', OrderedDict([('row1', 1), ('row2', 2)])),
             ('col2', OrderedDict([('row1', 0.5), ('row2', 0.75)]))])

If you want a `defaultdict`, you need to initialize it:

>>> dd = defaultdict(list)
>>> df.to_dict('records', into=dd)
[defaultdict(<class 'list'>, {'col1': 1, 'col2': 0.5}),
   defaultdict(<class 'list'>, {'col1': 2, 'col2': 0.75})]

DateFrame去重

# drop_duplicates(subset,keep,inplace,ignore_index)
# 去除完全相同的行
df.drop_duplicates(keep="first",inplace=True)
# 去某(些)除列有相同的行
df.drop_duplicates(subset=['columns1','columns2'],keep="last",inplace=True)
# - ``first`` : Drop duplicates except for the first occurrence.
# - ``last`` : Drop duplicates except for the last occurrence.

DateFrame新增列

# 在最后插入列
df.insert(df.shape[1],"columns","666")
# 插入列到首列 这个数字也可以指定,但是不能超过df.shape[1]
df.insert(0,"columns","666")

DateFrame 新增行

new=pd.DataFrame({
    'name':'lisa',
    'gender':'F',
    'city':'北京',
    'age':19,
    'score':100
    },
    index=[1] # 自定义索引,也可不设置index
)   

df=df.append(new,ignore_index=True)   # ignore_index=True,表示不按原来的索引,从0开始自动递增

DateFrame 计算日收益率、累计收益、最大回撤

# 日收益率
df.insert(0, "daily_return", df["price"].pct_change(1))
# 累计收益
df.insert(0,"cum_return",(df["daily_return"]+1).cumprod(axis=0)-1)
# 最大回撤
maxDrawDown = (df.price/df.price.cummax() - 1.0).cummin()

--更新中

posted @ 2021-05-14 18:05  Jacobyang  阅读(106)  评论(0编辑  收藏  举报