小编ajk*_*hol的帖子

在每列中查找DataFrame中不同元素的数量

我试图使用Pandas在每列中找到不同值的计数.这就是我做的.

import pandas as pd
import numpy as np

# Generate data.
NROW = 10000
NCOL = 100
df = pd.DataFrame(np.random.randint(1, 100000, (NROW, NCOL)),
                  columns=['col' + x for x in np.arange(NCOL).astype(str)])
Run Code Online (Sandbox Code Playgroud)

我需要计算每列的不同元素的数量,如下所示:

col0    9538
col1    9505
col2    9524
Run Code Online (Sandbox Code Playgroud)

最有效的方法是什么,因为此方法将应用于大小超过1.5GB的文件?


根据答案,df.apply(lambda x: len(x.unique()))是最快的(笔记本).

%timeit df.apply(lambda x: len(x.unique())) 10 loops, best of 3: 49.5 ms per loop %timeit df.nunique() 10 loops, best of 3: 59.7 ms per loop %timeit df.apply(pd.Series.nunique) 10 loops, best of 3: 60.3 ms per …

python numpy pandas

32
推荐指数
3
解决办法
4万
查看次数

工厂设计模式

我正在尝试实施工厂设计模式,并且到目前为止已经做到了这一点.

import abc

class Button(object):
    __metaclass__ = abc.ABCMeta

    html = ""
    def get_html(self, html):
        return self.html

class ButtonFactory():
    def create_button(self, type):
        baseclass = Button()
        targetclass = type.baseclass.capitalize()
        return targetclass

button_obj = ButtonFactory()
button = ['image', 'input', 'flash']
for b in button:
    print button_obj.create_button(b).get_html()
Run Code Online (Sandbox Code Playgroud)

输出应该是所有按钮类型的HTML.

我得到这样的错误

AttributeError: 'str' object has no attribute 'baseclass'
Run Code Online (Sandbox Code Playgroud)

我正在尝试实现一个具有不同变体的类,例如ImageButton,InputButton和FlashButton.根据地点的不同,可能需要为按钮创建不同的html

python design-patterns

13
推荐指数
2
解决办法
2万
查看次数

SQLAlchemy会话错误:InvalidRequestError

我试图提交以及从DB同时查询结果,我最终得到了这个错误.

sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
Run Code Online (Sandbox Code Playgroud)

完全追溯:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Python34\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "C:\Python34\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Python34\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Python34\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Python34\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Python34\lib\site-packages\flask\app.py", line 1381, …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy flask

11
推荐指数
1
解决办法
4685
查看次数

在文件中写入大量数据的最快方法

我试图创建一个随机的真实,整数,字母数字,字母字符串,然后写入文件,直到文件大小达到10MB.

代码如下.

import string
import random
import time
import sys


class Generator():
    def __init__(self):
        self.generate_alphabetical_strings()
        self.generate_integers()
        self.generate_alphanumeric()
        self.generate_real_numbers()

    def generate_alphabetical_strings(self):
        return ''.join(random.choice(string.ascii_lowercase) for i in range(12))

    def generate_integers(self):
        return ''.join(random.choice(string.digits) for i in range(12))

    def generate_alphanumeric(self):
        return ''.join(random.choice(self.generate_alphabetical_strings() +
                                     self.generate_integers()) for i in range(12))

    def _insert_dot(self, string, index):
        return string[:index].__add__('.').__add__(string[index:])


    def generate_real_numbers(self):
        rand_int_string = ''.join(random.choice(self.generate_integers()) for i in range(12))
        return self._insert_dot(rand_int_string, random.randint(0, 11))


from time import process_time
import os

a = Generator()

t = process_time()
inp = open("test.txt", …
Run Code Online (Sandbox Code Playgroud)

python performance file

11
推荐指数
1
解决办法
4万
查看次数

WSGI实用程序和Web服务器之间的区别

我是Python的新手,我无法理解Python中的服务器概念.

首先是什么是WSGI,什么是WsgirefWerkzeug,它们与CherryPy WSGI服务器,Gunicorn,Tornado(HTTP服务器通过wsgi.WSGIContainer),Twisted Web,uWSGI,Waitress WSGI Server有何不同.

如果我需要从头开始开发Web应用程序,我的意思是从头开始,我应该从哪里开始,我的公司需要一个自定义框架,而应用程序是基于关键的性能开销.

请帮助解释它们的不同之处.

PS我不是编程的初学者.

python wsgi

10
推荐指数
1
解决办法
2074
查看次数

Wsgiref错误:AttributeError:'NoneType'对象没有属性'split'

我正在尝试实现我自己的wsgiref版本用于学习目的,我最终在这里:

from wsgiref.simple_server import make_server

class DemoApp():
    def __init__(self, environ, start_response):
        self.environ = environ
        self.start = start_response

    def __iter__(self, status):
        self.status = '200 OK'
        response_headers = [('Content-type','text/plain')]
        self.start(status, response_headers)
        return ["Hello World"]


if __name__ == '__main__':
    httpd = make_server('', 1000, DemoApp)
    print("Serving on port 1000")
    httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

当我转到端口1000时,我收到属性错误.

AttributeError: 'NoneType' object has no attribute 'split'
Run Code Online (Sandbox Code Playgroud)

我在哪里留下错误?

堆栈跟踪:

Serving on port 1000
Traceback (most recent call last):
  File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run
    self.finish_response()
  File "C:\Python27\lib\wsgiref\handlers.py", line 131, in finish_response
    self.close()
  File …
Run Code Online (Sandbox Code Playgroud)

python wsgi

10
推荐指数
3
解决办法
9819
查看次数

ADT和类之间的区别?

ADT is the set of operations. ADT's are mathematical abstractions.
Run Code Online (Sandbox Code Playgroud)

这是否意味着ADT与班级相同或者我是否混淆在一起?

c abstract-data-type data-structures

8
推荐指数
2
解决办法
8074
查看次数

Django 1.6 urls无法正常工作

我是Django的新手,并试图弄清楚url如何在Django中工作.

我的应用程序是urls.py

from django.conf.urls import url, patterns
import views

urlpatterns = patterns('',
                       url(r'^$', views.index, name='index'))
Run Code Online (Sandbox Code Playgroud)

项目urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',

    url(r'^admin/', include(admin.site.urls)),
    url(r'^app/', include('app.urls')),
)
Run Code Online (Sandbox Code Playgroud)

APPEND_SLASH = True坐落在settings.py应用程序包含在INSTALLED_APPS.

当我去的时候,我得到了Page Not Foundlocalhost:8000/app.

现在我也无法前往localhost:8000/admin.

RuntimeError at /admin/
maximum recursion depth exceeded
Run Code Online (Sandbox Code Playgroud)

app的views.py

from django.http import HttpResponse

def index(request):
    return HttpResponse("This is Hello")
Run Code Online (Sandbox Code Playgroud)

Settings.py

import os
BASE_DIR = …
Run Code Online (Sandbox Code Playgroud)

python django

7
推荐指数
1
解决办法
2036
查看次数

Python是托管代码语言吗?

我在这里是NOOBish,但由于The Heartbleed Bug,我对托管代码非常感兴趣.

我最近在HN读到这句话,其中说:

C和其他没有内存检查的语言不适合编写安全代码.显然不合适.它们需要被限制为编写一个小型核心系统,最好小到可以使用正式(基于证据的)方法进行检查,其余所有应用程序逻辑都应该使用托管代码(例如C#, Java,或其他 - 我没有偏好).

那么Python是一种托管代码语言还是托管代码只是一个Microsoft术语?

c# python

5
推荐指数
2
解决办法
1658
查看次数

AttributeError:'str'对象没有属性'decode'Python3

这行在python 2.7.6中完美运行,但在Python 3.3.5中失败.我如何hex在Python 3中解码为值.

return x.replace(' ', '').replace('\n', '').decode('hex')
Run Code Online (Sandbox Code Playgroud)

追溯

AttributeError: 'str' object has no attribute 'decode'
Run Code Online (Sandbox Code Playgroud)

python

5
推荐指数
1
解决办法
1万
查看次数