Pandas 手册

Posted by luoruiqing on June 19, 2020

Pandas手册

Pandas生成随机数据

1
2
3
4
5
6
7
8
9
10
import numpy as np
import pandas as pd
import random

rows_len = random.randint(5, 10) # 行长度随机
cols_len = random.randint(5, 20) # 列长度随机

dates = pd.date_range('20200202', periods=rows_len)
columns= [f'C_{x}_{ random.randint(5, 1000) }'  for x in range(cols_len)] # 列名随机
df = pd.DataFrame(np.random.randn(rows_len, cols_len), index=dates,columns=columns )

Pandas 转 List

1
2
3
4
df = pd.DataFrame(data, columns=description)
df = df.reset_index() # 重置索引
headers = ['第一列名称'] + columns # 索引名称
body = list(row.tolist() for index,row in df.iterrows()) # 数据结果

Pandas 区域行列转置

1
2
3
df = pd.DataFrame(data, columns=columns)
sort_date=df.loc[df['GMV'] >0]["日期"].max()
df = pd.pivot_table(df, index=['日期'],columns=['分类'], values=['GMV'], aggfunc=lambda x: x).sort_values(by=sort_date, axis=1, ascending=True)