1. 导入python包
import numpy as np
import pandas as pd
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
2.造数据
csv='''
user_id,time_id,cnt
1,1,11
1,2,12
1,3,13
2,1,24
2,2,25
2,3,26
'''
with StringIO(csv) as f:
df = pd.read_csv(f)
print(df)
user_id time_id cnt
0 1 1 11
1 1 2 12
2 1 3 13
3 2 1 24
4 2 2 25
5 2 3 26
cnts = df.cnt.values
print(cnts)
[11 12 13 24 25 26]
3. 按照user_id, time_id 进行reshape操作
a = cnts.reshape((2,-1))
print(a)
[[11 12 13]
[24 25 26]]
(a[:,0:1].T).dot(a).sum()
180
4. 按照time_id, user_id进行reshape操作
4.1 第一种方案,使用转置操作
- 第一步:先按照user_id, time_id 进行reshape操作
- 第二步:再对新生产的数据进行转置操作
a = cnts.reshape((2,-1))
a = a.T
a
array([[11, 24],
[12, 25],
[13, 26]], dtype=int64)
4.2 第二种方案,使用reshape方法的属性order
- reshape:order的值默认是C(行),改为F(列)
a = cnts.reshape((-1, 2))
a
array([[11, 12],
[13, 24],
[25, 26]], dtype=int64)