我的尝试:
import numpy as np
np.seterr(divide='ignore')
a=np.array([4/3,0,0])
b=np.array([1,0,0])
np.divide(a,b)
Run Code Online (Sandbox Code Playgroud)
我得到的输出:
__main__:1: RuntimeWarning: invalid value encountered in true_divide
array(1.33333333, nan, nan])
Run Code Online (Sandbox Code Playgroud)
如果我再问:
np.divide(a,b)
Run Code Online (Sandbox Code Playgroud)
然后不显示 RuntimeWarning。
我对输出的数组很满意,但我不想要错误消息;这就是我认为 seterr 会解决的问题。我怎样才能摆脱警告?(我宁愿不写一个为 0/0 设置例外的 for 循环。)
我有一个包含许多列的数据集,我想找到n响应少于唯一响应的列,并将这些列更改为因子。
这是我能够做到的一种方法:
#create sample dataframe
df <- data.frame("number" = c(1,2.7,8,5), "binary1" = c(1,0,1,1),
"answer" = c("Yes","No", "Yes", "No"), "binary2" = c(0,0,1,0))
n <- 3
#for each column
for (col in colnames(df)){
#check if the first entry is numeric
if (is.numeric(df[col][1,1])){
# check that there are fewer than 3 unique values
if ( length(unique(df[col])[,1]) < n ) {
df[[col]] <- factor(df[[col]])
}
}
}
Run Code Online (Sandbox Code Playgroud)
实现这一目标的另一种方式是什么,希望更简洁?
我正在尝试从位于某个URL的文件加载数据.我使用请求来获取它(这很快发生).但是,使用r.json()来格式化部分字典大约需要10分钟.我怎样才能加快速度呢?
match_list = []
for i in range(1, 11):
r = requests.get('https://s3-us-west-1.amazonaws.com/riot-api/seed_data/matches%d.json' % i)
print('matches %d of 10 loaded' % i)
match_list.append(r.json()['matches'])
print('list %d of 10 created' % i)
match_histories = {}
match_histories['matches'] = match_list
Run Code Online (Sandbox Code Playgroud)
我知道这里有一个相关的问题:性能问题转换JSON数据 , but I don't see how I can apply that to my case. Thanks! (I'm using Python 3).
编辑:
我得到了很多看似有希望的建议,但每次都遇到了障碍.
我想尝试cjson,但我无法安装它(pip找不到MS visual C++ 10.0,尝试使用Lua进行一些安装,但我需要cl在我的路径中开始;).
json.loads(r.content)在Python 3中导致TypeError.
I'm not sure how to get ijson working.
ujson seems to take about as long as json …
我发现了其他人对 fmt 的使用,并试图使其适应我的目的。但是,尽管在这里阅读了它,但我还是不明白:http : //docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html。我希望我的数据在我保存的文本文件中的每一列中居中(或者让它看起来以某种方式组织起来,老实说,只要列以某种方式对齐我不在乎)。现在我让第一行左对齐,然后我的数据之间有均匀的空间。由于我数组中的每个条目的长度都不相同,这会导致数据发生偏移。如何对齐每列中的条目?
import numpy as np
my_list =['str123456789', 'str2', 'str3']
my_list2=[1,2458734750,3]
my_array=np.array(my_list)
my_array2=np.array(my_list2)
combined=np.column_stack([my_array,my_array2])
np.savetxt('test_file_name.txt', combined, fmt='{0: ^{1}}'.format("%s", 12))
Run Code Online (Sandbox Code Playgroud)
它在整体之间提供了均匀的空间,但我希望条目对齐。
左对齐或右对齐都可以。一条评论建议使用 {0:<{1}} 或 {0:>{1}} 代替 {0: ^{1}};然而,这并没有以任何不同的方式对齐我的数据。
我猜 .format("%s", 12) 使每个字符串为 12 个字符(在没有字符时添加空白字符),导致对齐问题。但是,如果我编写 .format("%s"),则会出现错误。fmt='%s',正在工作,但同样没有对齐。