我试图使用Python的ftplib读取文件而不编写它们.大致相当于:
def get_page(url):
try:
return urllib.urlopen(url).read()
except:
return ""
Run Code Online (Sandbox Code Playgroud)
但使用FTP.
我试过了:
def get_page(path):
try:
ftp = FTP('ftp.site.com', 'anonymous', 'passwd')
return ftp.retrbinary('RETR '+path, open('page').read())
except:
return ''
Run Code Online (Sandbox Code Playgroud)
但这不起作用.文档中的唯一示例涉及使用该ftp.retrbinary('RETR README', open('README', 'wb').write)格式编写文件.是否可以在不先写入的情况下读取ftp文件?
是否有一个内置的javascript函数,其功能类似于python的os.path.join?我知道我可以通过以下方式加入字符串:
['a', 'b'].join('/')
Run Code Online (Sandbox Code Playgroud)
问题是如果字符串已经包含前导/尾随"/",那么它们将无法正确连接,例如:
['a/','b'].join('/')
Run Code Online (Sandbox Code Playgroud)
编辑: 应该已经指定我正在做这个客户端.
堆叠大熊猫时DataFrame,Series会返回a.通常在我堆叠之后DataFrame,我将其转换回来DataFrame.但是,来自堆叠数据的默认名称使列重命名有点hacky.我正在寻找的是一种更简单/内置的方法,可以在堆叠后为列提供合理的名称.
例如,对于以下内容DataFrame:
In [64]: df = pd.DataFrame({'id':[1,2,3],
...: 'date':['2015-09-31']*3,
...: 'value':[100, 95, 42],
...: 'value2':[200, 57, 27]}).set_index(['id','date'])
In [65]: df
Out[65]:
value value2
id date
1 2015-09-31 100 200
2 2015-09-31 95 57
3 2015-09-31 42 27
Run Code Online (Sandbox Code Playgroud)
我将它堆叠并转换回DataFrame类似的:
In [68]: df.stack().reset_index()
Out[68]:
id date level_2 0
0 1 2015-09-31 value 100
1 1 2015-09-31 value2 200
2 2 2015-09-31 value 95
3 2 2015-09-31 value2 57
4 3 …Run Code Online (Sandbox Code Playgroud) 我正在使用包含数字和字母数字的字符串,或仅包含数字,但不仅仅是alpha.为了测试错误匹配,我需要检查字符串是否包含至少一个数字,如果没有则打印错误消息.我一直在使用以下代码:
s = '0798237 sh 523-123-asdjlh'
def contains_digits(s):
for char in list(s):
if char.isdigit():
return True
break
return False
if contains_digits(s) == True:
print s
else:
print 'Error'
Run Code Online (Sandbox Code Playgroud)
是否有更多的pythonic或更简单的方法,或者这是否足够?另外,我不能只检查字符串是否是字母数字,因为字符串可能包含各种符号(' - ',空格等)
是否有pandas功能允许根据条件从不同的列中进行选择?这类似于SQL Select子句中的CASE语句.例如,假设我有以下DataFrame:
foo = DataFrame(
[['USA',1,2],
['Canada',3,4],
['Canada',5,6]],
columns = ('Country', 'x', 'y')
)
Run Code Online (Sandbox Code Playgroud)
我希望在Country =='USA'时从列'x'中选择,在Country =='Canada'时从列'y'中选择,产生如下内容:
Country x y z
0 USA 1 2 1
1 Canada 3 4 4
2 Canada 5 6 6
[3 rows x 4 columns]
Run Code Online (Sandbox Code Playgroud) 当我尝试将if_exists='replace'参数传递给to_sql我时出现编程错误,告诉我该表已经存在:
>>> foobar.to_sql('foobar', engine, if_exists=u'replace')
...
ProgrammingError: (ProgrammingError) ('42S01', "[42S01] [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named 'foobar' in the database. (2714) (SQLExecDirectW)") u'\nCREATE TABLE foobar...
Run Code Online (Sandbox Code Playgroud)
从文档中听起来这个选项应该删除表并重新创建它,这不是观察到的行为.如果表已经不存在,则工作正常.任何想法,如果这是一个错误或我做错了什么?
我正在使用pandas 0.14和sqlalchemy 0.8.3以及enthought canopy python发行版,我正在连接到SQL Server.
编辑 按照joris的评论:
>>>pd.__version__
Out[4]: '0.14.0'
>>>pd.io.sql.has_table('foobar', engine)
Out[7]: False
>>>foobar.to_sql('foobar', engine, if_exists=u'replace', index=False)
---------------------------------------------------------------------------
ProgrammingError Traceback (most recent call last)
<ipython-input-9-2f4ac7ed7f23> in <module>()
----> 1 foobar.to_sql('foobar', engine, if_exists=u'replace', index=False)
C:\Users\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\generic.pyc in to_sql(self, name, con, flavor, if_exists, index, index_label)
948 sql.to_sql( …Run Code Online (Sandbox Code Playgroud) pandas合并功能似乎有一个怪癖.它认为NaN值相等,并将NaNs与其他NaNs 合并:
>>> foo = DataFrame([
['a',1,2],
['b',4,5],
['c',7,8],
[np.NaN,10,11]
], columns=['id','x','y'])
>>> bar = DataFrame([
['a',3],
['c',9],
[np.NaN,12]
], columns=['id','z'])
>>> pd.merge(foo, bar, how='left', on='id')
Out[428]:
id x y z
0 a 1 2 3
1 b 4 5 NaN
2 c 7 8 9
3 NaN 10 11 12
[4 rows x 4 columns]
Run Code Online (Sandbox Code Playgroud)
这与我见过的任何RDB都不同,通常缺少的值用不可知论来处理,并且不会被合并在一起,就好像它们是相同的一样.对于具有稀疏数据的数据集,这尤其成问题(每个NaN将合并到每个其他NaN,从而产生巨大的DataFrame!)
有没有办法在合并期间忽略缺失值而不先将它们切片出来?
我正在使用numpy创建一个边长为100的立方体数组,因此总共包含100万个条目.对于每百万个条目,我插入一个100x100矩阵,其条目由随机生成的数字组成.我使用以下代码来执行此操作:
import random
from numpy import *
cube = arange(1000000).reshape(100,100,100)
for element in cube.flat:
matrix = arange(10000).reshape(100,100)
for entry in matrix.flat:
entry = random.random()*100
element = matrix
Run Code Online (Sandbox Code Playgroud)
我期待这需要一段时间,但是生成了100亿个随机数,我不确定我的电脑是否可以处理它.这样一个阵列会占用多少内存?RAM是一个限制因素,即如果我的计算机没有足够的RAM,它是否无法实际生成阵列?
此外,如果有更高效的实现此代码,我会很感激提示:)
我正在尝试将当前目录更改C:为Y:
我尝试过:
import os
os.chdir('Y:')
Run Code Online (Sandbox Code Playgroud)
但我一直收到一个错误,说它找不到驱动器.基本上我正在寻找相当于
cd /d
Run Code Online (Sandbox Code Playgroud)
cmd中的命令.
我在我的计算机上安装了Python 2.7,MySQL 5.5,MySQL ODBC Connector 5.1和pyodbc,它运行的是Windows 7,64位......
唯一的问题是除了pyodbc(32位)外,一切都安装为64位.
当使用easy_install下载pyodbc时,它会自动下载32位版本.因此,当我尝试使用以下方法连接到我的数据库时:
cnxn = pyodbc.connect('DRIVER={MySQL ODBC 5.1 DRIVER};SERVER=localhost;DATABASE=test;UID=root;PWD=password')
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Data source name not found and no default driver specified (0) (SQLDriverConnect)
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下命令指定DSN时:
cnxn = pyodbc.connect('DSN=dsn_name;etc...')
Run Code Online (Sandbox Code Playgroud)
我收到错误:
The specified DSN contains an architecture mismatch between the Driver and Application (0) (SQLDriverConnect)
Run Code Online (Sandbox Code Playgroud)
此链接告诉我,这是由于32/64位不匹配,正如预期的那样:http: //msdn.microsoft.com/en-us/library/windows/desktop/ms712362(v = vs.85).aspx
所以我有两个问题:
1)是否可以强制easy_install下载64位pyodbc,还是可以手动下载64位pyodbc?
2)如果无法实现上述目的,是否可以使用Microsoft ODBC数据源管理器窗口配置DSN以允许此操作.
谢谢.