小编Abd*_*man的帖子

根据多个条件向 Python Pandas DataFrame 添加新列

我有一个包含各种列的数据集,如下所示:

discount tax total subtotal productid 3.98 1.06 21.06 20 3232 3.98 1.06 21.06 20 3232 3.98 6 106 100 3498 3.98 6 106 100 3743 3.98 6 106 100 3350 3.98 6 106 100 3370 46.49 3.36 66.84 63 695

现在,我需要添加一个新列Class并根据以下条件为其分配0或值1

if:
    discount > 20%
    no tax
    total > 100
then the Class will 1
otherwise it should be 0
Run Code Online (Sandbox Code Playgroud)

我在一个条件下完成了它,但我不知道如何在多个条件下完成它。

这是我尝试过的:

df_full['Class'] = df_full['amount'].map(lambda x: 1 if x > 100 else 0) …
Run Code Online (Sandbox Code Playgroud)

python numpy pandas

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

Python 从字典中写入 JSON 临时文件

我正在开发一个 python(3.6) 项目,在该项目中我需要从 Python 字典中编写一个 JSON 文件。

这是我的字典:

{'deployment_name': 'sec_deployment', 'credentials': {'type': 'type1', 'project_id': 'id_001',}, 'project_name': 'Brain', 'project_id': 'brain-183103', 'cluster_name': 'numpy', 'zone_region': 'europe-west1-d', 'services': 'Single', 'configuration': '', 'routing': ''}
Run Code Online (Sandbox Code Playgroud)

我需要将credentials密钥写入JSON 文件。

这是我尝试过的方法:

tempdir = tempfile.mkdtemp()
saved_umask = os.umask(0o077)
path = os.path.join(tempdir)
cred_data = data['credentials']
with open(path + '/cred.json', 'a') as cred:
    cred.write(cred_data)
credentials = prepare_credentials(path + '/cred.json')
print(credentials)
os.umask(saved_umask)
shutil.rmtree(tempdir)
Run Code Online (Sandbox Code Playgroud)

它不是在写一个 JSON 格式的文件,那么生成的文件是:

{
  'type': 'type1',
  'project_id': 'id_001',
}
Run Code Online (Sandbox Code Playgroud)

它带有单引号而不是双引号。

python json temporary-files python-3.x

7
推荐指数
2
解决办法
8118
查看次数

Python Sphinx css 在 github 页面上不起作用

我已经使用 Sphinx 为 Django 项目创建了文档,并html在执行make html命令后将文件夹的内容复制到docs/我的 repo 文件夹中并将其推送到 Github。之后,我将此docs/目录设置为Github Pages,现在它正在加载文档,但css不起作用,它只是带有任何样式的文档文本。

这是我的狮身人面像config.py

import os
import sys
import django
sys.path.insert(0, os.path.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'PROJECT_NAME.settings'
django.setup()

templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
html_theme = 'bizstyle'
html_static_path = ['_static']
BUILDDIR = '.'
Run Code Online (Sandbox Code Playgroud)

这是来自 GitHub 页面的文档页面的链接:https : //arycloud.github.io/Tagging-Project-for-Machine-Learning-Natural-Language-Processing/

有什么问题?

python django python-sphinx github-pages

7
推荐指数
3
解决办法
1241
查看次数

我们可以使用 .tar 或 zip 存档构建 docker 镜像吗

我们可以使用 tarball 或 zip 存档构建一个 docker 镜像,其中包含 dockerfile 吗?我需要使用 docker api 从档案构建图像。

有没有任何参考或资源,我搜索了 3o 分钟但找不到任何东西。

请帮帮我!提前致谢!

docker docker-image docker-build docker-api

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

Pandas 显示 Excel 文件的额外未命名列

我正在开发一个使用 pandas 库的项目,其中我需要读取一个包含以下列的 Excel 文件:

'invoiceid', 'locationid', 'timestamp', 'customerid', 'discount', 'tax',
   'total', 'subtotal', 'productid', 'quantity', 'productprice',
   'productdiscount', 'invoice_products_id', 'producttax',
   'invoice_payments_id', 'paymentmethod', 'paymentdetails', 'amount'
Run Code Online (Sandbox Code Playgroud)

但是当我使用下面的Python代码读取这个文件时:

df_full = pd.read_excel('input/invoiced_products_noinvoiceids_inproduct_v2.0.xlsx', sheet_name=0,)
df_full.head()
Run Code Online (Sandbox Code Playgroud)

它返回一些行和 6unnamed列,其值为NAN。我不知道为什么这些列显示在这里?

以下是请求的示例文件的链接:

https://mega.nz/#!0MlXCBYJ!Oim9RF56h6hUitTwqSG1354dIKLZEgIszzPrVpfHas8

为什么会出现这些额外的列?

python pandas

6
推荐指数
1
解决办法
7456
查看次数

在 Django Urls 中传递一个 URL 作为参数

我正在处理一个 Django(2) 项目,在该项目中我需要在 Django URL 中传递一个 URL 作为参数,这是我尝试过的:

网址.py:

urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/(?P<address>.*)/$', PerformImgSegmentation.as_view()),
]
Run Code Online (Sandbox Code Playgroud)

视图.py:

class PerformImgSegmentation(generics.ListAPIView):
    def get(self, request, *args, **kwargs):
        img_url = self.kwargs.get('address')
        print(img_url)
        print('get request')
    return 'Done'
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我address通过邮递员传递了一个名称为名称的参数,但它失败了。它返回此错误:

未找到:/api/ [05/Sep/2018 15:28:06] "GET /api/ HTTP/1.1" 404 2085

python django django-urls

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

如果在 Pandas DataFrame 中另一列不为空,则将一列替换为另一列

我正在使用 Pandas 处理数据框,如果另一个列值不为空,我必须在其中替换列。

我的数据框是这样的:

v_4        v5             s_5     vt_5     ex_5          pfv           pfv_cat
0-50      StoreSale     Clothes   8-Apr   above 100   FatimaStore       Shoes
0-50      StoreSale     Clothes   8-Apr   0-50        DiscountWorld     Clothes
51-100    CleanShop     Clothes   4-Dec   51-100      BetterUncle       Shoes
Run Code Online (Sandbox Code Playgroud)

所以,我想v_5pfvwhere pfvis not null替换,我该如何实现呢?

python dataframe pandas

6
推荐指数
3
解决办法
9675
查看次数

Python - 从图像中检测二维码并使用 OpenCV 进行裁剪

我正在使用 Python(3.7) 和 OpenCV 处理一个项目,其中我有一个文档的图像(使用相机捕获),上面放置了 QR 码。

此二维码有 6 个变量,分别为:

  1. 二维码图片尺寸

  2. 最佳

  3. 底部

  4. 剩下

  5. 单元


最新更新:

以下是我需要按相同顺序执行的步骤:

  1. 检测二维码并将其解码以读取大小值
  2. 因此,如果 QR 码(图像)的大小不等于其中提到的大小,则将图像缩放为等于两个大小值。
  3. 然后根据二维码中提到的值从二维码图像向四面八方裁剪图像。

我试过这个代码:

def decodeAndCrop(inputImage):
    print(str(inputImage))
    image = cv2.imread(str(inputImage))
    qrCodeDetector = cv2.QRCodeDetector()
    decodedText, points, _ = qrCodeDetector.detectAndDecode(image)
    qr_data = decodedText.split(",")
    print("qr data from fucntion: {}".format(qr_data))
    if points is not None:
        pts = len(points)
    # print(pts)
    for i in range(pts):
        nextPointIndex = (i + 1) % pts
        if str(inputImage) == "scaled_img.jpg":
            cv2.line(
                image,
                tuple(points[i][0]),
                tuple(points[nextPointIndex][0]),
                (255, 0, 0),
                5,
            ) …
Run Code Online (Sandbox Code Playgroud)

python opencv qr-code object-detection computer-vision

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

Python 临时文件 [Errno 66] 目录不为空

我需要处理从 db 对象生成的一些文件,并且在所需的过程之后需要删除该目录和文件。我决定使用 python Templefile 包。我已经尝试过但坚持了下来Direcotry not Empty [ Error 66 ].

views.py中

def writeFiles(request, name):
    tmpdir = tempfile.mkdtemp()
    instance = request.user.instances.get(name=name)
    print(instance)
    print(instance.name)
    code = instance.serverFile
    jsonFile = instance.jsonPackageFile
    docker = """
    FROM node
    # Create app directory
    RUN mkdir -p /usr/src/app
    WORKDIR /usr/src/ap

    # Install app dependencies
    COPY package.json /usr/src/app/
    RUN npm install

    # Bundle app source
    COPY . /usr/src/app

    EXPOSE 8080
    CMD [ "node", "server" ]"""
    # Ensure the file is read/write by the creator …
Run Code Online (Sandbox Code Playgroud)

python django django-views python-3.x

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

Google's Vision Api protobuf response object to Python dictionary

I'm working on a project in which I need to analyze an image using Google's Vision API and post the response to a Dynamodb table.

I have successfully implemented the Vision API, but not able to convert its response into Python Dictionary.

Here's what I have tried:

       if form.is_valid():
            obj = form
            obj.imageFile = form.cleaned_data['imageFile']
            obj.textFile = form.cleaned_data['textFile']
            obj.save()
            print(obj.imageFile)
            # Process the image using Google's vision API
            image_path = os.path.join(settings.MEDIA_ROOT, 'images/', obj.imageFile.name)
            print(image_path)
            image = vision_image_manager(image_path)
            text_path = os.path.join(settings.MEDIA_ROOT, …
Run Code Online (Sandbox Code Playgroud)

python protocol-buffers google-cloud-vision google-protocol-buffer

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