我正在尝试编写一个代码来确定自1970年初以来的毫秒数何时将超过long的容量.以下代码似乎可以完成这项工作:
public class Y2K {
public static void main(String[] args) {
int year = 1970;
long cumSeconds = 0;
while (cumSeconds < Long.MAX_VALUE) {
// 31557600000 is the number of milliseconds in a year
cumSeconds += 3.15576E+10;
year++;
}
System.out.println(year);
}
}
Run Code Online (Sandbox Code Playgroud)
此代码在几秒钟内执行并打印292272992.如果不是使用科学记数法,我将cumSeconds写为31558000000L,程序似乎"永远"运行(我只是在10分钟左右后暂停).另请注意,以科学计数形式写入cumSeconds不需要指定数字最后为longL或l.
我想自动选择列表框中的第一项.通过选择第一项,我并不仅仅意味着默认为第一项或设置焦点.我已经做到了这一点self.listbox.select_set(0).我想要也选择默认项目.换句话说,当我在下面运行我的代码时,我想print(value)打印默认选择的值.如果从选项菜单中选择亚洲,日本应自动打印到控制台.如果非洲,尼日利亚应该打印,德国打印到欧洲.
有关如何实现这一目标的任何建议?谢谢.
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
class App:
def __init__(self):
self.master = Tk()
self.di = {'Asia': ['Japan', 'China', 'Malaysia', 'India', 'Korea',
'Vietnam', 'Laos', 'Thailand', 'Singapore',
'Indonesia', 'Taiwan'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia', 'Ghana',
'Congo', 'Senegal', 'Guinea', 'Mali', 'Cameroun',
'Benin', 'Tanzania', 'South Africa', 'Zimbabwe']}
self.variable_a = StringVar()
self.frame_optionmenu = ttk.Frame(self.master)
self.frame_optionmenu.pack()
options = sorted(self.di.keys())
self.optionmenu = ttk.OptionMenu(self.frame_optionmenu, self.variable_a, options[0], *options)
self.variable_a.set('Asia')
self.optionmenu.pack()
self.btn = ttk.Button(self.master, text="Submit", …Run Code Online (Sandbox Code Playgroud) 似乎grep在返回匹配的方式上是"贪婪的".假设我有以下数据:
Sources <- c(
"Coal burning plant",
"General plant",
"coalescent plantation",
"Charcoal burning plant"
)
Registry <- seq(from = 1100, to = 1103, by = 1)
df <- data.frame(Registry, Sources)
Run Code Online (Sandbox Code Playgroud)
如果我执行grep("(?=.*[Pp]lant)(?=.*[Cc]oal)", df$Sources, perl = TRUE, value = TRUE),它会返回
"Coal burning plant"
"coalescent plantation"
"Charcoal burning plant"
Run Code Online (Sandbox Code Playgroud)
但是,我只想返回完全匹配,即只发生"煤"和"植物"的地方.我不想要"合并","种植园"等.所以对此,我只想看"Coal burning plant"
使用SettingWithCopyWarning,有时它会指向您模块中触发警告的确切代码行(例如此处),而其他时候则不会(例如此处)。
没有遍历代码的每一行(如果您正在查看数百行代码,这听起来不太吸引人),是否有一种方法可以确定触发警告的代码行,前提是警告没有返回该信息?
我想知道这是否是警告中的一个错误,即返回警告而没有查明触发它的特定代码。
Warning (from warnings module):
File "C:\Python34\lib\site-packages\pandas\core\indexing.py", line 415
self.obj[item] = s
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
Run Code Online (Sandbox Code Playgroud)
Python 3.4,熊猫 0.15.0
我有14个数据帧,每个数据帧有14列和超过250,000行。数据框具有相同的列标题,我想逐行合并数据框。我试图将数据帧连接到一个“不断增长的” DataFrame,这需要几个小时。
本质上,我做了13次以下操作:
DF = pd.DataFrame()
for i in range(13):
DF = pd.concat([DF, subDF])
Run Code Online (Sandbox Code Playgroud)
这里的stackoverflow答案建议将所有子数据帧附加到列表中,然后串联子数据帧列表。
听起来像这样:
DF = pd.DataFrame()
lst = [subDF, subDF, subDF....subDF] #up to 13 times
for subDF in lst:
DF = pd.concat([DF, subDF])
Run Code Online (Sandbox Code Playgroud)
他们不是同一回事吗?也许我误会了建议的工作流程。这是我测试过的。
import numpy
import pandas as pd
import timeit
def test1():
"make all subDF and then concatenate them"
numpy.random.seed(1)
subDF = pd.DataFrame(numpy.random.rand(1))
lst = [subDF, subDF, subDF]
DF = pd.DataFrame()
for subDF in lst:
DF = pd.concat([DF, subDF], axis=0,ignore_index=True)
def test2():
"add each …Run Code Online (Sandbox Code Playgroud) 假设我有一本字典,
mydict = { "short bread": "bread",
"black bread": "bread",
"banana cake": "cake",
"wheat bread": "bread" }
Run Code Online (Sandbox Code Playgroud)
给定字符串"wheat bread breakfast today"我想检查字典中是否包含字典中的任何键.如果是这样,我想返回与该键相关联的字典中的值.
我想为此使用列表理解.
这是我到目前为止所拥有的.
mykeys = mydict.keys()
mystring = "wheat breads breakfast today"
if any(s in string for s in mykeys):
print("Yes")
Run Code Online (Sandbox Code Playgroud)
这Yes按预期输出.我真正想要做的是使用s变量索引到mydict.但是sany()函数的范围有限.所以以下方法不起作用.
if any(s in mystring for s in mykeys):
print(mydict[s])
Run Code Online (Sandbox Code Playgroud)
任何解决方法?非常感谢!
我试图在Python中计算缺失值,并且sklearn似乎没有超出平均值(均值,中位数或模式)插补的方法.橙色插补模型似乎提供了一个可行的选择.然而,似乎Orange.data.Table没有认识到np.nan或以某种方式归因于失败.
import Orange
import numpy as np
tmp = np.array([[1, 2, np.nan, 5, 8, np.nan], [40, 4, 8, 1, 0.2, 9]])
data = Orange.data.Table(tmp)
imputer = Orange.feature.imputation.ModelConstructor()
imputer.learner_continuous = Orange.classification.tree.TreeLearner(min_subset=20)
imputer = imputer(data )
impdata = imputer(data)
for i in range(0, len(tmp)):
print impdata[i]
Run Code Online (Sandbox Code Playgroud)
输出是
[1.000, 2.000, 1.#QO, 5.000, 8.000, 1.#QO]
[40.000, 4.000, 8.000, 1.000, 0.200, 9.000]
Run Code Online (Sandbox Code Playgroud)
知道我错过了什么吗?谢谢!
在我的数据集中,我接近200行,但是对于最小的工作,例如,让我们假设以下数组:
arr = np.array([[1,2,3,4], [5,6,7,8],
[9,10,11,12], [13,14,15,16],
[17,18,19,20], [21,22,23,24]])
Run Code Online (Sandbox Code Playgroud)
我可以对3行进行随机抽样,如下所示:
indexes = np.random.choice(np.arange(arr.shape[0]), int(arr.shape[0]/2), replace=False)
Run Code Online (Sandbox Code Playgroud)
使用这些索引,我可以选择我的测试用例如下:
testing = arr[indexes]
Run Code Online (Sandbox Code Playgroud)
我想删除这些索引处的行,我可以将剩余的元素用于我的训练集.
从这里的帖子看来,似乎training = np.delete(arr, indexes)应该这样做.但我得到了1d阵列.
我也试过的建议在这里使用training = arr[indexes.astype(np.bool)],但它并没有给出清晰的分离.我在训练和测试集中都得到了元素[5,6,7,8].
training = arr[indexes.astype(np.bool)]
testing
Out[101]:
array([[13, 14, 15, 16],
[ 5, 6, 7, 8],
[17, 18, 19, 20]])
training
Out[102]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
Run Code Online (Sandbox Code Playgroud)
知道我做错了什么吗?谢谢.
假设我有以下pandas.Series:
import pandas as pd
s = pd.Series([1,3,5,True,6,8,'findme', False])
Run Code Online (Sandbox Code Playgroud)
我可以使用in运算符来查找任何整数或布尔值.例子,以下全部产生True:
1 in s
True in s
Run Code Online (Sandbox Code Playgroud)
但是,当我这样做时,这会失败:
'findme' in s
Run Code Online (Sandbox Code Playgroud)
我的解决方法是使用pandas.Series.str或首先将Series转换为列表,然后使用in运算符:
True in s.str.contains('findme')
s2 = s.tolist()
'findme' in s2
Run Code Online (Sandbox Code Playgroud)
知道为什么我不能直接使用in运算符来查找系列中的字符串吗?
我是python和编程的新手,需要一些帮助替换列表字典中的项目.我想,以取代None与'None'下面的词典:
dict = {'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', None],
'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', None],
'Rochester100': ['Caeser, Julius', '08/18/2014', '12/17/2014', None],
'Rochester101': [None, None, None, '08/18/2012']}
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
new_dict = {}
for i in dict: #This accesses each dictionary key.
temp = []
for j in dict[i]: #This iterates through the inner lists
if j is None:
temp.append('None')
else:
temp.append(j)
temp2 = {str(i):temp}
new_dict.update(temp2)
print(new_dict)
Run Code Online (Sandbox Code Playgroud)
产量
{'Chester100': ['Caesar, Augustus', '05/10/2012', '09/09/2012', 'None'],
'Rochester102': ['Henrich, Norton', '08/18/2014', '12/17/2014', …Run Code Online (Sandbox Code Playgroud) 请帮助我看看下面我缺少什么。我首先创建了班级的三个对象,并将它们添加到集合列表中。在创建任何其他对象之前,我要检查以确保该人在列表中不存在。如果此人已经存在,则不应再次创建该人。我希望通过执行此检查if prompt_fname == person.fname and prompt_lname == person.lname:。显然,我没有正确执行此操作,因为该程序仍然运行并创建了列表中已经存在的同一个人。它创造了这个人两次。我该如何进行修改以捕获此信息,以便不再创建列表中已有的人。同样,不应在循环的每次迭代中一次又一次地创建任何新人员。我是编程新手,所以请不要在答案中遗漏太多细节。非常感谢。
class Person(object):
personslist = []
'''Creates a person object'''
def __init__(self, firstname, lastname):
self.lname = lastname.title()
self.fname = firstname.title()
Person.personslist.append(self)
def __str__(self):
return "{0} {1}".format(self.fname, self.lname)
def __repr__(self):
return "{0} {1}".format(self.fname, self.lname)
Person("Adamu", "Emeka")
Person("Femi", "Ojukwu")
Person("Wole", "Jonathan")
prompt_fname = "Adamu"
prompt_lname = "Emeka"
print(Person.personslist)
for person in Person.personslist:
if prompt_fname == person.fname and prompt_lname == person.lname:
pass
else:
Person(prompt_fname, prompt_lname)
print(Person.personslist)
Run Code Online (Sandbox Code Playgroud)
产量
[Adamu Emeka, Femi Ojukwu, …Run Code Online (Sandbox Code Playgroud) 的基本语法DELETE是
DELETE FROM table
WHERE condition
Run Code Online (Sandbox Code Playgroud)
是否有一种直接的方法可以在DELETE语句中使用子查询/别名,如下所示?
DELETE FROM (subquery) as sub
WHERE condition
Run Code Online (Sandbox Code Playgroud)
下面是一个最小的工作表,我尝试使用子查询/别名失败:
---create table
create table orderT (
id integer PRIMARY KEY,
country_code varchar(2),
created_date date,
closed_date date);
---populate table
INSERT INTO orderT VALUES (1, 'US', now(), now() + interval '1 day' * 21);
INSERT INTO orderT VALUES (2, 'CA', now(), now() + interval '1 day' * 35);
--This does not work
DELETE
FROM
(SELECT *
FROM orderT) AS sub
WHERE sub.id = …Run Code Online (Sandbox Code Playgroud) python ×9
pandas ×3
python-3.x ×3
dictionary ×2
list ×2
numpy ×2
arrays ×1
for-loop ×1
imputation ×1
java ×1
listbox ×1
long-integer ×1
nested-loops ×1
optionmenu ×1
orange ×1
postgresql ×1
python-2.7 ×1
r ×1
regex ×1
scikit-learn ×1
sql ×1
sql-delete ×1
subquery ×1
tkinter ×1