我搜索了sklearn文档 TimeSeriesSplit
和交叉验证文档,但我找不到一个有效的例子.
我正在使用sklearn版本0.19.
这是我的设置
import xgboost as xgb
from sklearn.model_selection import TimeSeriesSplit
from sklearn.grid_search import GridSearchCV
import numpy as np
X = np.array([[4, 5, 6, 1, 0, 2], [3.1, 3.5, 1.0, 2.1, 8.3, 1.1]]).T
y = np.array([1, 6, 7, 1, 2, 3])
tscv = TimeSeriesSplit(n_splits=2)
for train, test in tscv.split(X):
print(train, test)
Run Code Online (Sandbox Code Playgroud)
得到:
[0 1] [2 3]
[0 1 2 3] [4 5]
Run Code Online (Sandbox Code Playgroud)
如果我尝试:
model = xgb.XGBRegressor()
param_search = {'max_depth' : [3, 5]}
my_cv = TimeSeriesSplit(n_splits=2).split(X) …
Run Code Online (Sandbox Code Playgroud) 说我有
Y = np.array([2, 0, 1, 1])
Run Code Online (Sandbox Code Playgroud)
由此我想获得与形状的矩阵X (len(Y), 3)
.在这种特殊情况下,X的第一行应该在第二个索引上有一个,而在其他情况下为零.X的第二行应该在0索引上有一个,否则为零.要明确:
X = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [0, 1, 0]])
Run Code Online (Sandbox Code Playgroud)
我该如何制作这个矩阵?我开始了
X = np.zeros((Y.shape[0], 3))
Run Code Online (Sandbox Code Playgroud)
但后来无法弄清楚如何填充/填写索引列表中的那些
一如既往,谢谢你的时间!
请考虑以下数据帧
df_test = pd.DataFrame( {'a' : [1, 2, 8], 'b' : [np.nan, np.nan, 5], 'c' : [np.nan, np.nan, 4]})
df_test.index = ['one', 'two', 'three']
Run Code Online (Sandbox Code Playgroud)
这使
a b c
one 1 NaN NaN
two 2 NaN NaN
three 8 5 4
Run Code Online (Sandbox Code Playgroud)
我有一个列b和c的行替换字典.例如:
{ 'one': [3.1, 2.2], 'two' : [8.8, 4.4] }
Run Code Online (Sandbox Code Playgroud)
3.1和8.8替换列b,2.2和4.4替换列c,结果是
a b c
one 1 3.1 2.2
two 2 8.8 4.4
three 8 5 4
Run Code Online (Sandbox Code Playgroud)
我知道如何使用for循环进行这些更改:
index_list = ['one', 'two']
value_list_b = [3.1, 8.8]
value_list_c = [2.2, 4.4]
for …
Run Code Online (Sandbox Code Playgroud) 个体(索引从0到5)在两个位置之间进行选择:A和B.我的数据具有宽格式,包含因个体(ind_var)而异的特征以及仅根据位置(location_var)变化的特征.
例如,我有:
In [281]:
df_reshape_test = pd.DataFrame( {'location' : ['A', 'A', 'A', 'B', 'B', 'B'], 'dist_to_A' : [0, 0, 0, 50, 50, 50], 'dist_to_B' : [50, 50, 50, 0, 0, 0], 'location_var': [10, 10, 10, 14, 14, 14], 'ind_var': [3, 8, 10, 1, 3, 4]})
df_reshape_test
Out[281]:
dist_to_A dist_to_B ind_var location location_var
0 0 50 3 A 10
1 0 50 8 A 10
2 0 50 10 A 10
3 50 0 1 B 14
4 50 0 3 …
Run Code Online (Sandbox Code Playgroud) 考虑一下这个dataFrame:
df = pd.DataFrame({u'A': {2.0: 2.2,
7.0: 1.4,
8.0: 1.4,
9.0: 2.2}, u'B': {2.0: 7.2,
7.0: 6.3,
8.0: 4.4,
9.0: 5.0}})
Run Code Online (Sandbox Code Playgroud)
看起来像这样:
A B
2 2.2 7.2
7 1.4 6.3
8 1.4 4.4
9 2.2 5.0
Run Code Online (Sandbox Code Playgroud)
我想得到带标签的索引2
和7
(数字,而不是字符串)
df.loc[[2, 7]]
Run Code Online (Sandbox Code Playgroud)
给出错误!
IndexError: indices are out-of-bounds
Run Code Online (Sandbox Code Playgroud)
然而,df.loc[7]
与df.loc[2]
做工精细,并符合预期.另外,如果我用字符串而不是数字定义数据框索引:
df2 = pd.DataFrame({u'A': {'2': 2.2,
'7': 1.4,
'8': 1.4,
'9': 2.2},
u'B': {'2': 7.2,
'7': 6.3,
'8': 4.4,
'9': 5.0}})
df2.loc[['2', '8']]
Run Code Online (Sandbox Code Playgroud)
它工作正常.
这不是我期望的行为df.loc
(它是一个bug还是只是一个陷阱?)我可以将一组数字作为标签索引传递而不仅仅是位置吗?
我可以将所有索引转换为字符串,然后进行操作, …
两张桌子:schools
和students
.SQLite中的索引(或多个密钥)将是id
与time
用于students
表和school
与time
该schools
表.我的数据集是关于不同的东西,但我认为学生的例子更容易理解.
import pandas as pd
import numpy as np
import sqlite3
df_students = pd.DataFrame(
{'id': list(range(0,4)) + list(range(0,4)),
'time': [0]*4 + [1]*4, 'school': ['A']*2 + ['B']*2 + ['A']*2 + ['B']*2,
'satisfaction': np.random.rand(8)} )
df_students.set_index(['id', 'time'], inplace=True)
satisfaction school
id time
0 0 0.863023 A
1 0 0.929337 A
2 0 0.705265 B
3 0 0.160457 B
0 1 0.208302 A
1 1 0.029397 …
Run Code Online (Sandbox Code Playgroud) 我有类似的东西
df = pd.DataFrame(np.random.randint(2, 10, size = (5, 2)))
df.index = pd.MultiIndex.from_tuples([(1, 'A'), (2, 'A'), (4, 'B'),
(5, 'B'), (8, 'B')])
df.index.names = ['foo', 'bar']
df.columns = ['count1', 'count2']
df
Run Code Online (Sandbox Code Playgroud)
这使:
count1 count2
foo bar
1 A 6 7
2 A 2 9
4 B 6 7
5 B 4 6
8 B 5 6
Run Code Online (Sandbox Code Playgroud)
我还有一个总计列表 - 从其他地方获得 - 通过相同的'foo'索引:
totals = pd.DataFrame([2., 1., 1., 1., 10.])
totals.index = [1, 2, 4, 5, 8]
totals.index.names = ['foo']
totals
Run Code Online (Sandbox Code Playgroud)
这使:
0 …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 NTILE 函数从 pandas 查询 SQLite 数据库,但我没有成功,尽管我已经多次重新检查了语法。
下面是独立的示例。设置:
import pandas as pd
from sqlalchemy import create_engine
disk_engine = create_engine('sqlite:///test.db')
marks = pd.DataFrame({'StudentID': ['S1', 'S2', 'S3', 'S4', 'S5'],
'Marks': [75, 83, 91, 83, 93]})
marks.to_sql('marks_sql', disk_engine, if_exists='replace')
Run Code Online (Sandbox Code Playgroud)
现在尝试使用 NTILE:
q = """select StudentID, Marks, NTILE(2) OVER (ORDER BY Marks DESC)
AS groupexample FROM marks_sql"""
pd.read_sql_query(q, disk_engine)
Run Code Online (Sandbox Code Playgroud)
回溯很长,但主要部分是:
OperationalError: near "(": syntax error
OperationalError: (sqlite3.OperationalError) near "(": syntax error [SQL: 'select StudentID, Marks, NTILE(2) OVER (ORDER BY Marks DESC)\n AS groupexample FROM …
Run Code Online (Sandbox Code Playgroud) 我觉得我忽略了一些非常简单的事情,但我无法让它发挥作用。我现在正在使用SQLite
,但解决方案SQLAlchemy
也将非常有帮助。
让我们创建原始数据集:
### This is just the setup part
import pandas as pd
import sqlite3
conn = sqlite3.connect('test.sqlite')
orig = pd.DataFrame({'COLUPC': [100001, 100002, 100003, 100004],
'L5': ['ABC ALE', 'ABC MALT LIQUOR', 'ABITA AMBER', 'ABITA AMBER'],
'attr1': [0.25, 0.25, 0.041, 0.041]})
orig.to_sql("UPCs", conn, if_exists='replace', index=False)
#Create an index just in case it's needed
conn.execute("""CREATE INDEX upc_index
ON UPCs (COLUPC);""")
Run Code Online (Sandbox Code Playgroud)
现在假设我接受orig
dataframe
并添加一个名为“L5_lower”的列。然后我在 SQLite 数据库中创建列:
# Create new variable
orig['L5_lower'] = orig.L5.str.lower()
conn.execute("alter table UPCs add column …
Run Code Online (Sandbox Code Playgroud) 我正在运行Mac OS Maverick.
在我之前的设置中,绘图将正确显示在RStudio的绘图选项卡上.我重新安装R with homebrew
,当我使用RStudio时,它给了我以下警告
警告:您运行的R版本不支持石英图形设备(RStudio要求图形设备)."Plots"选项卡将被禁用,直到安装了支持quartz的R版本.
当我绘制一些东西时,它会XQuartz
在我的Mac上打开应用程序.它确实显示了图形(有时虽然有奇怪的颜色),但我真的很喜欢它在RStudio中绘制.
是不是homebrew
有一个版本R
不支持石英图形设备或我搞砸了其他地方的东西?
与往常一样,任何帮助将非常感谢.
我的设置的一些细节:
R版本3.1.2(2014-10-31) - "南瓜头盔"
RStudio版本0.98.1091
平台:x86_64-apple-darwin13.4.0(64位).Mac OS 10.9.5
我R
用homebrew
以下方式安装
brew tap homebrew/science
brew install r
以前我安装tcl/tk
了以下方式
brew tap homebrew/dupes
brew install tcl-tk --with-tk
从2000年到2010年,我有30多个地区的密度数据.我想为每年创建一个交互式的等值区域地图,然后使用滑块(理想情况下)或单选按钮来选择年份.
我可以在第一年获得互动,但不会在其他年份的层次上.你可以在这里看到一个有用的例子,但是让我在下面提供一些细节:
为简单起见,请考虑两年.blocks1995
具有非重叠多边形BlockA和BlockB(两个区)并blocks1996
具有相同的块.他们有一个叫做density
产生等值的财产:
var blocks1995 = {
"type": "FeatureCollection",
"crs": {
"type": "name",
"properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" }
},
"features": [{
"type": "Feature",
"properties": { "time": 1995, "density": 3.1, "nameB": "BlockA" },
"geometry": {
"type": "Polygon",
"coordinates": [[[50.0, 29.0],[50.0, 29.99],[50.51, 29.99],[50.0, 29.0]]]
}
}, {
"type": "Feature",
"properties": { "time": 1995, "density": 1.1, "nameB": "BlockB" },
"geometry": {
"type": "Polygon",
"coordinates": [[[50.01, 30.0],[50.52, 30.0],[50.52, 30.5]]]
}
}]
};
var blocks1996 …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 Dask 从 google 存储桶读取和写入。使用一堆csv
文件可以,但不方便(速度较慢,无法压缩,无法仅读取某些列),所以我尝试使用该apache parquet
格式。
看起来写得很好:
import dask.dataframe as dd
pandas_df = pd.DataFrame({'x' : [2,3, 2], 'y': [1, 0, 0]})
dask_df = dd.from_pandas(pandas_df, npartitions=2)
dask_df.to_parquet("gcs://my_google_bucket/test/")
Run Code Online (Sandbox Code Playgroud)
但当我尝试读回来时
read_again_df = dd.read_parquet("gcs://my_google_bucket/test/")
Run Code Online (Sandbox Code Playgroud)
我收到一个未实现的错误:
AttributeError Traceback (most recent call last)
~/miniconda3/envs/env1/lib/python3.6/site-packages/dask/bytes/core.py in get_pyarrow_filesystem(fs)
520 try:
--> 521 return fs._get_pyarrow_filesystem()
522 except AttributeError:
AttributeError: 'DaskGCSFileSystem' object has no attribute '_get_pyarrow_filesystem'
During handling of the above exception, another exception occurred:
NotImplementedError Traceback (most recent call last)
<ipython-input-42-ef1fc41d04d5> in <module>()
----> 1 …
Run Code Online (Sandbox Code Playgroud) 我正在为大量用户收集推文,因此该脚本将在无人监督的情况下运行数天/数周.我有一个user_ids列表big_list
.我认为有些推文是私有的,我的脚本会停止,所以我想让脚本继续使用下一个user_id(并且可能会打印一条警告消息).
我还想了解如何使其对其他错误或异常具有鲁棒性(例如,脚本在出错或超时时休眠)
这是我的总结:
import tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
my_api = tweepy.API(auth)
for id_str in big_list:
all_tweets = get_all_tweets(id_str=id_str, api=my_api)
#Here: insert some tweets into my database
Run Code Online (Sandbox Code Playgroud)
该get_all_tweets
函数抛出错误,它基本上反复调用:
my_api.user_timeline(user_id = id_str, count=200)
Run Code Online (Sandbox Code Playgroud)
以防万一,它给出的回溯如下:
/home/username/anaconda/lib/python2.7/site-packages/tweepy/binder.pyc in execute(self)
201 except Exception:
202 error_msg = "Twitter error response: status code = %s" % resp.status
--> 203 raise TweepError(error_msg, resp)
204
205 # Parse the response payload
TweepError: Not authorized.
Run Code Online (Sandbox Code Playgroud)
如果您需要更多详细信息,请告诉我们.谢谢!
-----------编辑--------
这个问题有一些信息.
我想我可以尝试try/except
为不同类型的错误做一个块?我不知道所有相关的,所以有现场经验的人的最佳实践将不胜感激!
----------编辑2 …
python ×11
pandas ×7
sqlite ×3
choropleth ×1
dask ×1
database ×1
geo ×1
homebrew ×1
interactive ×1
javascript ×1
leaflet ×1
macos ×1
numpy ×1
parquet ×1
pyarrow ×1
r ×1
reshape ×1
rstudio ×1
scikit-learn ×1
sql ×1
sqlalchemy ×1
tweepy ×1
twitter ×1
xgboost ×1