需要组合多个具有2列的矩阵,如下所示
matrix1
1,3
1,5
3,6
matrix2
1,4
1,5
3,6
3,7
output
1,3,1
1,4,1
1,5,2
3,6,2
3,7,1
Run Code Online (Sandbox Code Playgroud)
输出中的第三列是在所有矩阵中看到一对的次数.我写了一些代码来做到这一点
require(data.table)
set.seed(1000)
data.lst <- lapply(1:200, function(n) { x <- matrix(sample(1:1000,2000,replace=T), ncol=2); x[!duplicated(x),] })
#method 1
pair1.dt <- data.table(i=integer(0), j=integer(0), cnt=integer(0))
for(mat in data.lst) {
pair1.dt <- rbind(pair1.dt, data.table(i=mat[,1],j=mat[,2],cnt=1))[, .(cnt=sum(cnt)), .(i,j)]
}
#method 2
pair2.dt <- data.table(i=integer(0), j=integer(0), cnt=integer(0))
for(mat in data.lst) {
pair2.dt <- merge(pair2.dt, data.table(i=mat[,1],j=mat[,2],cnt=1), by=c("i","j"), all=T)[,
cnt:=rowSums(.SD,na.rm=T), .SDcols=c("cnt.x","cnt.y")][, c("cnt.x","cnt.y"):=NULL]
}
cat(sprintf("num.rows => pair1: %d, pair2: %d", pair1.dt[,.N], pair2.dt[,.N]), "\n")
Run Code Online (Sandbox Code Playgroud)
在实际问题中,每个矩阵具有数百万行,并且可能有30-40%的重叠.我试图找出最快的方法来做到这一点.我尝试使用Matrix :: …
[python 3.5.2, pandas 0.24.1, numpy 1.16.1, scipy 1.2.0]
我有以下熊猫数据框
data_pd
nrows: 1,032,749,584
cols: ['mem_id':np.uint32, 'offset':np.uint16 , 'ctype':string, 'code':string]
obsmap_pd
nrows: 10,887,542
cols: ['mem_id':np.uint32, 'obs_id':np.uint32]
(obs_id has consecutive integers between 0 and obsmap_pd nrows)
varmap_pd
nrows: 4,596
cols: ['ctype':string, 'code': string, 'var_id':np.uint16]
(var_id has consecutive integers between 0 and varmap_pd nrows)
Run Code Online (Sandbox Code Playgroud)
这些是我正在执行的步骤
***
sparse_pd = data_pd.groupby(['mem_id','ctype','code'])['offset'].nunique().reset_index(name='value')
sparse_pd['value'] = sparse_pd['value'].astype(np.uint16)
sparse_pd = pd.merge(pd.merge(sparse_pd, obsmap_pd, on='mem_id', sort=False),
varmap_pd, on=['ctype','code'], sort=False)[['obs_id','var_id','value']]
***
Run Code Online (Sandbox Code Playgroud)
这样做的目的是在下一步中创建一个scipy csc_matrix
mat_csc = csc_matrix((sparse_pd['value'].values*1., (sparse_pd['obs_id'].values,sparse_pd['var_id'].values)),
shape=(obsmap_pd.shape[0],varmap_pd.shape[0]))
Run Code Online (Sandbox Code Playgroud)
csc_matrix的创建速度非常快,但是使用熊猫代码的三行代码(***之间)需要25.7分钟。关于如何加快速度的任何想法?
我有一个稀疏矩阵(x)和一个数组(y).我想计算矩阵中每列与数组之间的相关性.下面显示的是一种非常简单的方法,这种方法很慢.我希望有人会有更快/更好的方法.
import numpy as np
from scipy.sparse import rand as r1
from numpy.random import rand as r2
np.random.seed(1000)
nrow,ncol = 50000,4000
x = r1(nrow, ncol, format='csr', density=.05)
y = (r2(nrow)<=.6).astype(int)
correl = [(n,np.corrcoef(np.asarray(x[:,n].todense()).reshape(-1), y)[0,1]) for n in xrange(ncol)]
print correl[:10]
Run Code Online (Sandbox Code Playgroud) 版本:Python 3.7.6,pandas 1.0.0
输入数据框
df = pd.DataFrame(dict(
recruit_dt=["1/1/2017"]*3+["1/1/2018"]*3+["1/1/2019"]*3,
label = [1,3,4]*3,
nmem = np.random.choice(list(range(10000,3000000)),9),
pct_fem = np.random.sample(9),
mean_age = 50 + 10*np.random.sample(9),
sd_age = 8 + 2*np.random.sample(9)
))
Run Code Online (Sandbox Code Playgroud)
想在以下转换后呈现此内容
dfp = pd.pivot_table(df, values=["nmem","pct_fem","mean_age","sd_age"], index="recruit_dt", columns="label")
dfp = dfp.reindex(columns=['nmem', 'pct_fem', 'mean_age', 'sd_age'], level=0)
Run Code Online (Sandbox Code Playgroud)
如何编写样式器,以便所有nmem列都有千位分隔符{:,},“pct_fem”是保留两位小数的百分比,mean_age并且sd_age是带有两位小数的浮点数?有没有一种使用styler.formator styler.applywith 的方法IndexSlice?
== 编辑:这似乎有效。有没有更简洁的解决方案?
dfp.columns.names = ["metrics","label"]
dfp.style.format("{:,}", subset=pd.IndexSlice[:,'nmem']) \
.format("{:.2%}", subset=pd.IndexSlice[:,'pct_fem']) \
.format("{:.2f}", subset=pd.IndexSlice[:,['mean_age','sd_age']])
Run Code Online (Sandbox Code Playgroud) 我有一个pandas数据帧,其索引为numpy数组.对于那些索引,数组的值必须设置为1.我需要在一个大的numpy阵列上做这个数百万次.有没有比下面显示的方法更有效的方法?
from numpy import float32, uint
from numpy.random import choice
from pandas import DataFrame
from timeit import timeit
xy = 2000,300000
sz = 10000000
ind = DataFrame({"i":choice(range(xy[0]),sz),"j":choice(range(xy[1]),sz)}).drop_duplicates()
dtype = uint
repeats = 10
#original (~21s)
stmt = '''\
from numpy import zeros
a = zeros(xy, dtype=dtype)
a[ind.values[:,0],ind.values[:,1]] = 1'''
print(timeit(stmt, "from __main__ import xy,sz,ind,dtype", number=repeats))
#suggested by @piRSquared (~13s)
stmt = '''\
from numpy import ones
from scipy.sparse import coo_matrix
i,j = ind.i.values,ind.j.values
a = coo_matrix((ones(i.size, dtype=dtype), (i, j)), dtype=dtype).toarray() …Run Code Online (Sandbox Code Playgroud) 下面这段代码的输出是
import numpy, random, pandas
random.seed(10000)
sz = 1000000
pd = pandas.DataFrame({"x":random.choices(range(2), k=sz), "y":random.choices(range(3), k=sz)})
pd["values"] = 1
pd.pivot_table(index="x", columns="y", aggfunc="count", margins=True)
Run Code Online (Sandbox Code Playgroud)
如下所示
values
y 0 1 2 All
x
0 166575.0 166726.0 166553.0 499854.0
1 166823.0 166366.0 166957.0 500146.0
All 333398.0 333092.0 333510.0 1000000.0
Run Code Online (Sandbox Code Playgroud)
如何添加格式语句以便打印计数时不带尾随 .0。我不希望使用pandas.set_option可能改变此会话中所有数据帧的行为的 a 来执行此操作。
我试图让 xaxis 标签中的 <= 正确显示。我看过以前的帖子expression。在每个示例中,只有 1 个标签是显式(手动)完成的。就我而言,有几个带有 <= 的标签。我从文件中读取了因子标签。
faclab <- "value,label
1,<= 1
2,1 < ... <= 2
3,2< ... <= 3
4,>3"
labels.dt <- fread(faclab)
data <- data.table(value=sample(labels.dt[['value']],100,replace=TRUE))
ggplot(data, aes(factor(value))) + geom_bar(aes(y=(..count..)/sum(..count..))) +
scale_x_discrete(breaks=labels.dt[['value']], labels=labels.dt[['label']])
Run Code Online (Sandbox Code Playgroud) 我的输入数据具有以下格式
id offset code
1 3 21
1 3 24
1 5 21
2 1 84
3 5 57
3 5 21
3 5 92
3 10 83
3 10 21
Run Code Online (Sandbox Code Playgroud)
我希望输出格式如下
id offset code
1 [3,5] [[21,24],[21]]
2 [1] [[84]]
3 [5,10] [[21,57,92],[21,83]]
Run Code Online (Sandbox Code Playgroud)
我能够提出的代码如下所示
import random, pandas
random.seed(10000)
param = dict(nrow=100, nid=10, noffset=8, ncode=100)
#param = dict(nrow=1000, nid=10, noffset=8, ncode=100)
#param = dict(nrow=100000, nid=1000, noffset=50, ncode=5000)
#param = dict(nrow=10000000, nid=10000, noffset=100, ncode=5000)
pd = pandas.DataFrame({ …Run Code Online (Sandbox Code Playgroud)