假设我有一些简单的数据
y = [[datetime.datetime( 2012,1,1,1,1), 2.1],
[datetime.datetime( 2012,1,1,1,2), -3.1],
[datetime.datetime( 2012,1,1,1,3), 0.1]]
Run Code Online (Sandbox Code Playgroud)
我想要一个与之对应的numpy记录数组.看起来我应该能够做到这一点:
np.rec.array( y, dtype=[('timestamp', object),('x','f')] )
Run Code Online (Sandbox Code Playgroud)
或这个
np.rec.array( y, dtype=[('timestamp', '|O8'),('x','f')] )
Run Code Online (Sandbox Code Playgroud)
或许这个
np.rec.array( y, dtype=[('timestamp', 'V'),('x','f')] )
Run Code Online (Sandbox Code Playgroud)
但他们每个人都会返回一个错误
ValueError: Setting void-array with object members using buffer.
Run Code Online (Sandbox Code Playgroud)
要么
TypeError: expected a readable buffer object
Run Code Online (Sandbox Code Playgroud)
那么假设它甚至可能,我怎么能设置它呢?
我更喜欢使用defaultsContinuum提供的常用频道中的MKL工具链.但是,和许多人一样,我发现自己从conda-forge频道安装了不少套餐.
例如,考虑python-graphviz包.安装命令是
conda install -c conda-forge python-graphviz
Run Code Online (Sandbox Code Playgroud)
这导致一些不希望的依赖变化
The following packages will be UPDATED:
cvxopt: 1.1.7-py27_0 --> 1.1.9-py27_blas_openblas_201 conda-forge [blas_openblas]
gsl: 2.2.1-h8267d9d_2 --> 2.2.1-blas_openblas_2 conda-forge [blas_openblas]
numpy: 1.13.3-py27hbcc08e0_0 --> 1.13.3-py27_blas_openblas_200 conda-forge [blas_openblas]
scikit-learn: 0.19.1-py27h445a80a_0 --> 0.19.1-py27_blas_openblas_200 conda-forge [blas_openblas]
scipy: 0.19.1-py27h1edc525_3 --> 0.19.1-py27_blas_openblas_202 conda-forge [blas_openblas]
Run Code Online (Sandbox Code Playgroud)
我不想更改为OpenBlas numpy,因此我手动处理所有依赖项然后
conda install -c conda-forge --no-deps python-graphviz
Run Code Online (Sandbox Code Playgroud)
这工作正常,但很费力,并会招致错误.
我原以为如果我添加conda-forge了低优先级通道
conda config --append channels conda-forge
Run Code Online (Sandbox Code Playgroud)
然后它会停止尝试覆盖numpy安装,但事实证明这是不真实的.conda config --show正如预期的那样,现在的输出包含
channel_alias: https://conda.anaconda.org
channel_priority: True
channels: …Run Code Online (Sandbox Code Playgroud) 我一直在计算带有子选择和一些聚合函数的NULL和非NULL列
CREATE TEMPORARY TABLE citizens(name text, country text,profession text,postalcode text);
INSERT INTO citizens VALUES
('Fred', 'USA', 'Professor', NULL),
('Amy', 'USA', 'Professor', NULL),
('Ted', 'USA', 'Professor', 90210),
('Barb', 'USA', 'Lawyer', 10248),
('Wally', 'USA', 'Lawyer', NULL),
('Fred', 'Canada', 'Professor', 'S0H'),
('Charles', 'Canada', 'Professor', 'S4L'),
('Nancy', 'Canada', 'Lawyer', NULL),
('Linda', 'Canada', 'Professor', NULL),
('Steph', 'France', 'Lawyer', 75008 ),
('Arnold', 'France', 'Lawyer', 75008 ),
('Penny', 'France', 'Lawyer', 75008 ),
('Harry', 'France', 'Lawyer', NULL);
SELECT country,
profession,
MAX(have_postalcode::int*num) AS num_have,
MAX((1-have_postalcode::int)*num) AS num_not_have
FROM
( …Run Code Online (Sandbox Code Playgroud) 考虑到我有以下数据和函数返回我喜欢的汇总统计信息
landlines <- data.frame(
year=rep(c(1990,1995,2000,2005,2010),times=3),
country=rep(c("US", "Brazil", "Asia"), each=5),
pct = c(0.99, 0.99, 0.98, 0.05, 0.9,
0.4, 0.5, 0.55, 0.5, 0.45,
0.7, 0.85, 0.9, 0.85, 0.75)
)
someStats <- function(x)
{
dp <- as.matrix(x$pct)-mean(x$pct)
indp <- as.matrix(x$year)-mean(x$year)
f <- lm.fit( indp,dp )$coefficients
w <- sd(x$pct)
m <- min(x$pct)
results <- c(f,w,m)
names(results) <- c("coef","sdev", "minPct")
results
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样成功地将该函数应用于数据子集:
> someStats(landlines[landlines$country=="US",])
coef sdev minPct
-0.022400 0.410938 0.050000
Run Code Online (Sandbox Code Playgroud)
或按国家/地区细分如下:
> by(landlines, list(country=landlines$country), someStats)
country: Asia
coef sdev minPct
0.00200000 0.08215838 0.70000000
--------------------------------------------------------------------------------------- …Run Code Online (Sandbox Code Playgroud) 对于正负符号的非常重尾数据,我有时希望在单位区间内看到图中的所有数据而不隐藏结构.
在Python中使用Matplotlib进行绘图时,我可以通过选择一个symlog标度来实现这一点,该标度使用某个区间之外的对数变换,并在其中进行线性绘图.
之前在RI中,通过一次性转换arcsinh来构建类似的行为.但是,刻度标签等操作起来非常棘手(见下文).

现在,我面临着一堆数据,其中格子或ggplot中的子集非常方便.因为子集,我不想使用Matplotlib,但我确实缺少symlog!
我看到ggplot使用了一个名为scales的包,它解决了很多这个问题(如果它有效).自动选择刻度线和标签放置看起来仍然很难做得很好.一些组合log_breaks和cbreaks也许?
以下代码也不错
sinh.scaled <- function(x,scale=1){ sinh(x)*scale }
asinh.scaled <- function(x,scale=1) { asinh(x/scale) }
asinh_breaks <- function (n = 5, scale = 1, base=10)
{
function(x) {
log_breaks.callable <- log_breaks(n=n,base=base)
rng <- rng <- range(x, na.rm = TRUE)
minx <- floor(rng[1])
maxx <- ceiling(rng[2])
if (maxx == minx)
return(sinh.scaled(minx, scale=scale))
big.vals <- 0
if (minx …Run Code Online (Sandbox Code Playgroud) 我想使用psycopg2中提供的复制命令将旧数据库中的表行复制到新数据库中.我想我可以通过StringIO重定向,如下所示
io = StringIO.StringIO('')
whereClause = " SELECT %s FROM %s WHERE home_city='%s' "%(
','.join(columns), tablename, city,
)
old_db_cursor.execute(whereClause)
rows = old_db_cursor.fetchall()
logger.info('Should get %d rows',len([r for r in rows]))
sql = 'COPY (%s) to STDOUT'%(whereClause,)
old_db_cursor.copy_expert( sql, io, )
new_db_cursor.copy_from( io, tablename, columns=columns)
new_db_connection.commit()
Run Code Online (Sandbox Code Playgroud)
记录显示我应该获得30,000行.但是,尽管缺少错误消息,但我没有获得新行.为了它的价值,检查io.read()节目的长度为零.
我怎样才能做到这一点?
我有一个pandas.DataFrame,它不会像我期望的那样转动.虽然pivot_table妥善安排了一切,但它使用聚合函数来实现这一目标的事实令人反感.此外,pivot_table似乎返回一个不必要的复杂对象而不是平面数据框.
请考虑以下示例
import pandas as pd
df = pd.DataFrame({'firstname':['Jon']*3+['Amy']*2,
'lastname':['Cho']*3+['Frond']*2,
'vehicle':['bike', 'car', 'plane','bike','plane'],
'weight':[81.003]*3+[65.6886]*2,
'speed':[29.022, 95.1144, 302.952, 27.101, 344.2],})
df.set_index(['firstname','lastname','weight'])
print('------ Unnecessary pivot_table does averaging ------')
print(pd.pivot_table(df, values='speed',
rows='firstname','lastname','weight'],
cols='vehicle'))
print('------ pivot method dies ------')
print(df.pivot( index=['firstname','lastname','weight'],
columns='vehicle',
values='speed'))
Run Code Online (Sandbox Code Playgroud)
该pivot_table结果
vehicle bike car plane
firstname lastname weight
Amy Frond 65.6886 27.101 NaN 344.200
Jon Cho 81.0030 29.022 95.1144 302.952
Run Code Online (Sandbox Code Playgroud)
有没有办法pivot提供与pivot_table命令基本相同的输出(但希望更平坦和更整洁)?如果做不到这一点,我该如何压扁输出pivot_table?我想要的输出是更像这样的东西:
firstname lastname weight bike car plane …Run Code Online (Sandbox Code Playgroud) 我想创建一个PostgreSQL函数,它执行以下操作:
CREATE FUNCTION avg_purchases( IN last_names text[] DEFAULT '{}' )
RETURNS TABLE(last_name text[], avg_purchase_size double precision)
AS
$BODY$
DECLARE
qry text;
BEGIN
qry := 'SELECT last_name, AVG(purchase_size)
FROM purchases
WHERE last_name = ANY($1)
GROUP BY last_name'
RETURN QUERY EXECUTE qry USING last_names;
END;
$BODY$
Run Code Online (Sandbox Code Playgroud)
但我在这里看到两个问题:
当我这样做时,这当前返回零行:
SELECT avg_purchases($${'Brown','Smith','Jones'}$$);
Run Code Online (Sandbox Code Playgroud)我错过了什么?
arrays postgresql plpgsql aggregate-functions postgresql-9.2
我有一个 RDD,其分区包含可以轻松转换为行列表的元素(pandas 数据帧,碰巧)。把它想象成这样
rows_list = []
for word in 'quick brown fox'.split():
rows = []
for i,c in enumerate(word):
x = ord(c) + i
row = pyspark.sql.Row(letter=c, number=i, importance=x)
rows.append(row)
rows_list.append(rows)
rdd = sc.parallelize(rows_list)
rdd.take(2)
Run Code Online (Sandbox Code Playgroud)
这使
[[Row(importance=113, letter='q', number=0),
Row(importance=118, letter='u', number=1),
Row(importance=107, letter='i', number=2),
Row(importance=102, letter='c', number=3),
Row(importance=111, letter='k', number=4)],
[Row(importance=98, letter='b', number=0),
Row(importance=115, letter='r', number=1),
Row(importance=113, letter='o', number=2),
Row(importance=122, letter='w', number=3),
Row(importance=114, letter='n', number=4)]]
Run Code Online (Sandbox Code Playgroud)
我想把它变成一个 Spark DataFrame。我希望我能做到
rdd.toDF()
Run Code Online (Sandbox Code Playgroud)
但这给出了一个无用的结构
DataFrame[_1: struct<importance:bigint,letter:string,number:bigint>,
_2: struct<importance:bigint,letter:string,number:bigint>,
_3: struct<importance:bigint,letter:string,number:bigint>,
_4: struct<importance:bigint,letter:string,number:bigint>,
_5: …Run Code Online (Sandbox Code Playgroud)