我应该把shebang放在我的Python脚本中吗?以什么形式?
#!/usr/bin/env python
Run Code Online (Sandbox Code Playgroud)
要么
#!/usr/local/bin/python
Run Code Online (Sandbox Code Playgroud)
这些同样便携吗?哪种形式最常用?
我试图在Windows计算机上使用Python 3.2来编写一个简单的CSV文件,但是我没有运气.从Python 3.2的csv模块文档:
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ',
... quotechar='|', quoting=csv.QUOTE_MINIMAL)
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Run Code Online (Sandbox Code Playgroud)
生成一个文件,每行由字节序列终止\r\r\n
,因此当您用例如MS Excel打开它时,看起来每行都有一个额外的空行.这不是"CSV文件".
注意,如果我在Python 3.2中尝试Python 2.7的相同示例(其中'w'
与'wb'
文件模式的区别很大),我在尝试时遇到错误spamWriter.writerow
:
回溯(最近一次调用最后一次):TypeError中的文件"",第1行:'str'不支持缓冲区接口
如何在Windows计算机上从Python 3.2编写简单的CSV文件?
我创建了一个名为Options的类.它工作正常,但不是没有Python 2.我希望它可以在Python 2和3上工作.问题是:Python 2中不存在FileNotFoundError但是如果我使用IOError它在Python 3中不起作用
版本3.3中已更改:EnvironmentError,IOError,WindowsError,VMSError,socket.error,select.error和mmap.error已合并到OSError中.
我该怎么办?(请不要讨论我对便携性的选择,我有理由.)
这是代码:
#!/usr/bin/python
#-*-coding:utf-8*
#option_controller.py
#Walle Cyril
#25/01/2014
import json
import os
class Options():
"""Options is a class designed to read, add and change informations in a JSON file with a dictionnary in it.
The entire object works even if the file is missing since it re-creates it.
If present it must respect the JSON format: e.g. keys must be strings and so on.
If something corrupted the file, just destroy the file or …
Run Code Online (Sandbox Code Playgroud) 如何计算矩阵中的矩阵平均值,但是nan
要从计算中删除值?(对R人来说,想想na.rm = TRUE
).
这是我的[非]工作示例:
import numpy as np
dat = np.array([[1, 2, 3],
[4, 5, np.nan],
[np.nan, 6, np.nan],
[np.nan, np.nan, np.nan]])
print(dat)
print(dat.mean(1)) # [ 2. nan nan nan]
Run Code Online (Sandbox Code Playgroud)
删除NaN后,我的预期输出为:
array([ 2., 4.5, 6., nan])
Run Code Online (Sandbox Code Playgroud) 我有数千万行从多维数组文件传输到PostgreSQL数据库.我的工具是Python和psycopg2.批量处理数据的最有效方法是使用copy_from
.但是,我的数据大多是32位浮点数(real或float4),所以我宁愿不转换为real→text→real.这是一个示例数据库DDL:
CREATE TABLE num_data
(
id serial PRIMARY KEY NOT NULL,
node integer NOT NULL,
ts smallint NOT NULL,
val1 real,
val2 double precision
);
Run Code Online (Sandbox Code Playgroud)
这是我使用字符串(文本)使用Python的地方:
# Just one row of data
num_row = [23253, 342, -15.336734, 2494627.949375]
import psycopg2
# Python3:
from io import StringIO
# Python2, use: from cStringIO import StringIO
conn = psycopg2.connect("dbname=mydb user=postgres")
curs = conn.cursor()
# Convert floating point numbers to text, write to COPY input
cpy = StringIO()
cpy.write('\t'.join([repr(x) for x in …
Run Code Online (Sandbox Code Playgroud) 这是从" 将PostgreSQL的PL/pgSQL输出保存到CSV文件 "的答案中的后续问题.
我需要使用psql的\copy
命令编写客户端CSV文件.一个班轮工作:
db=> \copy (select 1 AS foo) to 'bar.csv' csv header
COPY 1
Run Code Online (Sandbox Code Playgroud)
但是,我有很长的查询,跨越几行.我不需要显示查询,因为我似乎无法在没有解析错误的情况下延伸过去一行:
db=> \copy (
\copy: parse error at end of line
db=> \copy ( \\
\copy: parse error at end of line
db=> \copy ("
\copy: parse error at end of line
db=> \copy "(
\copy: parse error at end of line
db=> \copy \\
\copy: parse error at end of line
Run Code Online (Sandbox Code Playgroud)
是否可以使用\copy
跨越多行的查询?我在Windows上使用psql.
这可能很容易解决.我有一个mat
500行×335列的2D矩阵和一个dat
120425行的data.frame.该data.frame dat
有两列I
和J
,它是整数索引的行,列的mat
.我想将值添加mat
到行的行中dat
.
这是我的概念失败:
> dat$matval <- mat[dat$I, dat$J]
Error: cannot allocate vector of length 1617278737
Run Code Online (Sandbox Code Playgroud)
(我在Win32上使用R 2.13.1).深入挖掘,我发现我误用了矩阵索引,因为看起来我只得到了一个子矩阵mat
,而不是我预期的单维数组值,即:
> str(mat[dat$I[1:100], dat$J[1:100]])
int [1:100, 1:100] 20 1 1 1 20 1 1 1 1 1 ...
Run Code Online (Sandbox Code Playgroud)
我期待着类似的东西int [1:100] 20 1 1 1 20 1 1 1 1 1 ...
.使用行,列索引索引2D矩阵以获取值的正确方法是什么?
我正在处理熊猫数据帧的各个行,但是在索引和插入行时遇到强制问题。熊猫似乎总是想将int / float混合类型强制转换为全浮点类型,而且我看不到对此行为有任何明显的控制。
例如,这是一个带有a
as int
和b
as 的简单数据框float
:
import pandas as pd
pd.__version__ # '0.25.2'
df = pd.DataFrame({'a': [1], 'b': [2.2]})
print(df)
# a b
# 0 1 2.2
print(df.dtypes)
# a int64
# b float64
# dtype: object
Run Code Online (Sandbox Code Playgroud)
在索引一行时,这是一个强制问题:
print(df.loc[0])
# a 1.0
# b 2.2
# Name: 0, dtype: float64
print(dict(df.loc[0]))
# {'a': 1.0, 'b': 2.2}
Run Code Online (Sandbox Code Playgroud)
这是插入一行时的强制问题:
df.loc[1] = {'a': 5, 'b': 4.4}
print(df)
# a b
# 0 1.0 2.2
# 1 …
Run Code Online (Sandbox Code Playgroud) 我使用PostgreSQL 9.1来查询分层树结构数据,包括与节点连接的边(或元素).数据实际上是用于流网络,但我已经将问题抽象为简单的数据类型.考虑示例tree
表.每条边都有长度和面积属性,用于确定网络中的一些有用指标.
CREATE TEMP TABLE tree (
edge text PRIMARY KEY,
from_node integer UNIQUE NOT NULL, -- can also act as PK
to_node integer REFERENCES tree (from_node),
mode character varying(5), -- redundant, but illustrative
length numeric NOT NULL,
area numeric NOT NULL,
fwd_path text[], -- optional ordered sequence, useful for debugging
fwd_search_depth integer,
fwd_length numeric,
rev_path text[], -- optional unordered set, useful for debugging
rev_search_depth integer,
rev_length numeric,
rev_area numeric
);
CREATE INDEX ON tree (to_node);
INSERT INTO …
Run Code Online (Sandbox Code Playgroud) postgresql recursive-query common-table-expression hierarchical-query transitive-closure-table
我想打印NumPy表格数组数据,以便它看起来不错.R和数据库控制台似乎表现出很好的能力.但是,NumPy的表格数组的内置打印看起来像垃圾:
import numpy as np
dat_dtype = {
'names' : ('column_one', 'col_two', 'column_3'),
'formats' : ('i', 'd', '|S12')}
dat = np.zeros(4, dat_dtype)
dat['column_one'] = range(4)
dat['col_two'] = 10**(-np.arange(4, dtype='d') - 4)
dat['column_3'] = 'ABCD'
dat['column_3'][2] = 'long string'
print(dat)
# [(0, 0.0001, 'ABCD') (1, 1.0000000000000001e-005, 'ABCD')
# (2, 9.9999999999999995e-007, 'long string')
# (3, 9.9999999999999995e-008, 'ABCD')]
print(repr(dat))
# array([(0, 0.0001, 'ABCD'), (1, 1.0000000000000001e-005, 'ABCD'),
# (2, 9.9999999999999995e-007, 'long string'),
# (3, 9.9999999999999995e-008, 'ABCD')],
# dtype=[('column_one', '<i4'), ('col_two', '<f8'), ('column_3', '|S12')])
Run Code Online (Sandbox Code Playgroud)
我希望看起来更像数据库吐出的东西,例如postgres风格: …
python ×7
postgresql ×3
python-3.x ×3
numpy ×2
binary-data ×1
bulkinsert ×1
client-side ×1
coercion ×1
csv ×1
file ×1
indexing ×1
matrix ×1
nan ×1
pandas ×1
pretty-print ×1
psql ×1
psycopg2 ×1
python-2.7 ×1
r ×1
r-faq ×1
shebang ×1
shell ×1
tabular ×1
windows ×1