我有一个 CHAR 列,其中包含对打印整数的凌乱 OCR 扫描。
我需要在该列上执行 SUM() 运算符。但我无法正确投射。
;Good
sqlite> select CAST("123" as integer);
123
;No Good, should be '323999'
sqlite> select CAST("323,999" as integer);
323
Run Code Online (Sandbox Code Playgroud)
我相信SQLite的解释逗号作为标志着“结束的值可能的最长前缀可以解释为一个整数”
我更愿意避免编写 python 脚本来对本专栏进行数据清理的痛苦。有没有什么聪明的方法可以严格地使用 SQL 来做到这一点?
我的数据帧具有各种类型的DateTime索引(可以是每周,每月,每年的数据).我想生成列为其他列的滞后值的列.我从电子表格中导入了这些,我没有在python中生成日期时间索引.
我正在努力寻找这种"pythonic"方式.我想如果我使用Pandas的日期时间功能,在奇怪或异常数据的情况下,滞后可能更强大.
我制作了一个似乎有效的玩具示例,但它在我的真实世界的例子中失败了.
正确工作的玩具示例(创建一个具有上个月'foo'值的新列)
rng = pd.date_range('2012-01-01', '2013-1-01', freq="M")
toy2 = pd.DataFrame(pd.Series(np.random.randint(0, 50, len(rng)), index=rng, name="foo"))
foo
2012-01-31 4
2012-02-29 2
2012-03-31 27
2012-04-30 7
2012-05-31 44
2012-06-30 22
2012-07-31 16
2012-08-31 18
2012-09-30 35
2012-10-31 35
2012-11-30 16
2012-12-31 32
toy2['lag_foo']= toy2['foo'].shift(1,'m')
foo lag_foo
2012-01-31 4 NaN
2012-02-29 2 4.0
2012-03-31 27 2.0
2012-04-30 7 27.0
2012-05-31 44 7.0
2012-06-30 22 44.0
2012-07-31 16 22.0
2012-08-31 18 16.0
2012-09-30 35 18.0
2012-10-31 35 35.0
2012-11-30 16 35.0
2012-12-31 32 …Run Code Online (Sandbox Code Playgroud) 这不是建议的重复项。我并不是想切换后端。我只是想尝试使用这个%matplotlib notebook公式。此外,其他问题中建议的解决方案(将其放在 OR 尝试连续两次调用魔术命令%matplotlib notebook之前from matplotlib import pylplot as plt)对我不起作用。行为(空白笔记本图表)仍然存在。
将 the 放在%matplotlib notebookthe 之前from matplotlib import pylplot as plt 尝试连续两次调用魔术命令
当我使用%matplotlib inline 我的图表时,总是会显示,但它们通常较小,并且无法缩放/平移。
当我使用时,%matplotlib notebook我会得到可缩放、可平移的图表,但有时会遇到图表显示为空白的问题。
背景:
PythonAnywhere 笔记本 3.6 Python。使用 Windows 7 中的更新 Google Chrome。
如果我重新打开现有的笔记本,甚至重新启动内核并重新运行所有单元格,所有单元格.plot()都会显示为空白。但如果我同时启动一台全新的 3.6 笔记本, %matplotlib notebook绘图效果很好。杀死所有与 jupyter 相关的进程也没有帮助。
这种情况并不总是发生。但如果一张图表显示为空白,则所有图表都显示为空白。
我想使用notebook魔法,但这个问题相当深奥。
我的字符串看起来像"co1/co2","co3/co4"......"co11/co12"
将其描述为正则表达式:
^(?P<prefix>\w\w)(?P<month>\d+)/(?P<prefix2>\w\w)(?P<month2>\d+)$
Run Code Online (Sandbox Code Playgroud)
我想根据正则表达式的"月"组的等价物对这些字符串的集合进行排序.(字符串中的第一个数字(例如,'co1/co2'中的"1"或'co12/co13中的"12")
我无法弄清楚我可以在sorted()中使用的lambda函数,它会为我做这个.
wrong_order = [u'co1/co2', u'co10/co11', u'co11/co12', u'co12/co13', u'co2/co3',
u'co3/co4', u'co4/co5', u'co5/co6', u'co6/co7', u'co7/co8', u'co8/co9',
u'co9/co10']
correct_order = [u'co1/co2', u'co2/co3', u'co3/co4', u'co4/co5', u'co5/co6', \
u'co6/co7', u'co7/co8', u'co8/co9', u'co9/co10', u'co10/co11', u'co11/co12', u'co12/co13']
#this lambda function doesn't work
output = sorted(wrong_order, key=lambda x: (x[2:]))
Run Code Online (Sandbox Code Playgroud) 我有一个大的DataFrame,就像
import pandas as pd
sqldate = pd.Series(["2014-0-1", "2015-10-10", "1990-23-2"])
pdf = pd.Series(["2014.pdf", "2015.pdf", "1999.pdf"])
df = pd.DataFrame({"sqldate":sqldate, "pdf": pdf})
Run Code Online (Sandbox Code Playgroud)
我想创建一个布尔列,指示sqldate的年份是否与pdf名称的年份相同.
另一种情况是forloop很容易做到这一点,但我想将其矢量化以提高速度/清洁度.但我无法弄清楚如何.
我尝试过更简单的方法,甚至只是制作一个df ['newcol']并尝试从日期中删除左边的四个字符.像df ['newcol'] = df ['sqldate'] [0:4]但是失败了.它只生成newcol = sqldate的前四行,其余行为Nan,因为它将[0:4]解释为索引选择器.
有关在数据帧上使用受控字符串值的更优雅,矢量化方式的任何建议吗?
我想要的:我的python脚本运行,将日志消息输出到控制台和文件.
一旦python脚本运行完毕,我希望能够删除/编辑日志文件.我在Windows7上使用Spyder IDE.
示例代码:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
hdlr = logging.FileHandler("/Users/mds/Dropbox/_python/logger-debug.txt")
logger.addHandler(hdlr)
logger.error("Am I duplicating error entries?")
hdlr.close()
Run Code Online (Sandbox Code Playgroud)
我遇到的问题:
我第一次运行脚本:
安慰:
runfile('C:/Users/mds/Dropbox/_python/logger-debugger.py', wdir='C:/Users/mds/Dropbox/_python')
ERROR:__main__:Am I duplicating error entries?
Run Code Online (Sandbox Code Playgroud)
记录仪,DEBUG.TXT:
Am I duplicating error entries?
Run Code Online (Sandbox Code Playgroud)
我第二次运行脚本: console:
runfile('C:/Users/mds/Dropbox/_python/logger-debugger.py', wdir='C:/Users/mds/Dropbox/_python')
ERROR:__main__:Am I duplicating error entries?
Run Code Online (Sandbox Code Playgroud)
记录仪,DEBUG.TXT
Am I duplicating error entries?
Am I duplicating error entries?
Am I duplicating error entries?
Run Code Online (Sandbox Code Playgroud)
我第三次运行脚本:
安慰:
runfile('C:/Users/mds/Dropbox/_python/logger-debugger.py', wdir='C:/Users/mds/Dropbox/_python')
ERROR:__main__:Am I duplicating error entries?
Run Code Online (Sandbox Code Playgroud)
记录仪,DEBUG.TXT
Am I duplicating error entries?
Am …Run Code Online (Sandbox Code Playgroud) 我从read_sql_query. 它有三栏,“结果,速度,重量”
我想用 scikit-learnLinearRegression来适应results = f(speed, weight)
我一直无法找到正确的语法来允许我将此数据框或其列切片传递给LinearRegression.fit(y, X).
print df['result'].shape
print df[['speed', 'weight']].shape
(8L,)
(8, 2)
Run Code Online (Sandbox Code Playgroud)
但我不能把它传递给 fit
lm.fit(df['result'], df[['speed', 'weight']])
Run Code Online (Sandbox Code Playgroud)
它抛出一个deprecation warning和一个ValueError
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19.
ValueError: Found arrays with inconsistent numbers of samples: [1 8]
Run Code Online (Sandbox Code Playgroud)
获取目标和特征的数据帧并将它们传递给fit操作的有效、干净的方法是什么?
这就是我生成示例的方式:
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
date_today = datetime.now()
days …Run Code Online (Sandbox Code Playgroud) 我正在使用用Python实现的Norvig的BASIC解释器.
有一些代码似乎与我无关,但这个人似乎超出了我的100级,所以我更有可能无法理解而不是写了一些不必要的东西.
def lines(text):
"A list of the non-empty lines in a text."
return [line for line in text.splitlines() if line]
#return [zaa for zaa in text.splitlines()]
Run Code Online (Sandbox Code Playgroud)
列表理解 - 为什么它完成if line?
如果我删除该子句,使用 [zaa for zaa in text.splitlines()]相反,我仍然认为该函数可以工作,如果我传递它文本甚至是一个空行.
foo ="""mike\nnew\nbar"""
bar ="\n\n"
print lines(foo)
print lines(bar)
what = lines(bar)
print(type(what))
['mike', 'new', 'bar']
[]
<type 'list'>
Run Code Online (Sandbox Code Playgroud)
我必须误解某些东西 - 我if line甚至无法理解何时对其进行评估,更不用说正确处理输入的必要性.
编辑:发现缺少的例子if line会给出不好的结果:
bar ="""one
two
three
five
seven"""
#bar = ""
print …Run Code Online (Sandbox Code Playgroud) 我正在尝试series用'pandas.tseries.index.DatetimeIndex'. x 轴标签顽固地重叠,即使有几个建议的解决方案,我也无法使它们呈现出来。
我尝试了 建议使用的 stackoverflow 解决方案,autofmt_xdate但它没有帮助。
我也尝试了对 的建议plt.tight_layout(),但没有产生效果。
ax = test_df[(test_df.index.year ==2017) ]['error'].plot(kind="bar")
ax.figure.autofmt_xdate()
#plt.tight_layout()
print(type(test_df[(test_df.index.year ==2017) ]['error'].index))
Run Code Online (Sandbox Code Playgroud)
更新:我使用条形图是一个问题。常规时间序列图显示管理良好的标签。
在制作熊猫数据框的条形图时,我一直在调试显示问题。
今天遇到一个奇怪的问题:
index: <class 'pandas.tseries.index.DatetimeIndex'>
count 83.000
mean 0.000
std 0.879
min -2.159
25% -0.605
50% 0.001
75% 0.658
max 2.254
Name: error, dtype: float64
Run Code Online (Sandbox Code Playgroud)
当我将数据绘制为时间序列时,它看起来不错:
plt.plot(errors.index, errors.values)
但是,如果我将其打印为条形图,则大多数条形图都不会出现:
plt.bar(errors.index, errors.values)
plt.gcf().autofmt_xdate()
Run Code Online (Sandbox Code Playgroud)
我认为条形图的数据条太多,无法很好地显示,但如果我直接从数据框中绘制条,则情况并非如此:
errors.plot(kind="bar")
但是,dataframe.plot 不能很好地处理这么多带有轴标签的条形……但它告诉我 plt.bar应该能够显示它。