小编Lui*_*uez的帖子

使用列表理解修改数据框列

我有一个包含大约 90k 个字符串的列表和一个包含多列的数据框,我有兴趣检查列表的字符串是否在 column_1 中,以及它是否在 column_2 中分配了相同的值。

我可以做这个:

for i in range(len(my_list)):
    item = list[i]
    for j in range(len(df)):
         if item == df['column_1'][j]:
             df['column_2'][j] = item
Run Code Online (Sandbox Code Playgroud)

但我宁愿避免嵌套循环

我试过这个

for item in my list:
    if item in list(df['column _1']):
          position = df[df['column_1']==item]].index.values[0]
          df['column_2'][position]  = item
Run Code Online (Sandbox Code Playgroud)

但我认为这个解决方案更慢更难阅读,这个操作可以通过简单的列表理解来完成吗?

编辑。

第二个解决方案要快得多,大约一个数量级。这是为什么?似乎在这种情况下它必须搜索两次以获得马赫:

这里:

if item in list(df['column _1'])
Run Code Online (Sandbox Code Playgroud)

和这里:

possition = df[df['column_1]=='tem]].index.values[0]
Run Code Online (Sandbox Code Playgroud)

我仍然更喜欢更简单的解决方案。

python pandas

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

是否可以将spacy保留在内存中以减少加载时间?

我想使用spacy和NLP进行在线服务.每次用户发出请求时,我都会调用脚本"my_script.py"

从以下开始:

from spacy.en import English
nlp = English()
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是这两行占用时间超过10秒,是否可以将英语()保留在ram或其他一些选项中以将此加载时间减少到不到一秒?

python nlp spacy

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

美丽的汤元内容标记

<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> 
Run Code Online (Sandbox Code Playgroud)

我必须得到内容'4103 Beach Bluff Rd'.我正试着这样做BeautifulSoup,我正在尝试这个:

soup = BeautifulSoup('<meta itemprop="streetAddress" content="4103 Beach Bluff Rd"> ')

soup.find(itemprop="streetAddress").get_text()
Run Code Online (Sandbox Code Playgroud)

但是我得到一个empy字符串作为结果,这可能有意义,因为当打印汤对象

print soup
Run Code Online (Sandbox Code Playgroud)

我明白了:

<html><head><meta content="4103 Beach Bluff Rd" itemprop="streetAddress"/> </head></html>
Run Code Online (Sandbox Code Playgroud)

显然,我想要的数据是在"元内容"标签中,我该如何获取这些数据?

html python beautifulsoup html-parsing

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

创建一个有序的字典

我有一个像这样的字典:

original_dict = {'two':'2','three':'3','one':'1','foo':'squirrel'}
Run Code Online (Sandbox Code Playgroud)

我想要两个按此顺序:

ordered_dict = OrderedDict({'one':'1','two':'2','three':'3','foo':'squirrel'})

但我没有得到相同的顺序, {'one':'1','two':'2','three':'3','foo':'squirrel'}自己创建一个字典,所以它不像我说的那样工作

我在文档中看到可以使用已排序的方法

OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
Run Code Online (Sandbox Code Playgroud)

但我不知道一个函数来返回我想要的命令

ordered_dict = OrderedDict(sorted(original_dict.items(),['one','two','three','foo']))
Run Code Online (Sandbox Code Playgroud)

但那没用.

请注意,我想要的顺序可以是任意的,例如:

['three','foo','one','two',]
Run Code Online (Sandbox Code Playgroud)

python dictionary

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

用scrapy下载整页

我想使用scrapy下载整页内容.

使用硒这很容易:

import os,sys
reload(sys)  
sys.setdefaultencoding('utf8')
from selenium import webdriver


url = 'https://es.wikipedia.org/wiki/Python'

driver = webdriver.Firefox()
driver.get(url)
content = driver.page_source
with open('source','w') as output:
    output.write(content)
Run Code Online (Sandbox Code Playgroud)

但是硒比scrapy慢得多.

在scrapy中这是一种简单的方法吗?

我想将每个页面的代码保存在不同的文件文本中,而不是csv或json文件.此外,如果没有创建项目可行,这对于这样一个简单的任务来说似乎有些过分.

python scrapy web-scraping

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

在两个步骤中使用字符串中的.format()

我有一个字符串,我想在其中替换一些变量,但在不同的步骤中,类似于:

my_string = 'text_with_{var_1}_to_variables_{var_2}'
my_string.format(var_1='10')
### make process 1
my_string.format(var_2='22')
Run Code Online (Sandbox Code Playgroud)

但是当我尝试替换第一个变量时,我得到一个错误:

KeyError: 'var_2'
Run Code Online (Sandbox Code Playgroud)

我怎么能做到这一点?

编辑:我想创建一个新列表:

name = 'Luis'
ids = ['12344','553454','dadada']
def create_list(name,ids):
    my_string = 'text_with_{var_1}_to_variables_{var_2}'.replace('{var_1}',name)
    return [my_string.replace('{var_2}',_id) for _id in ids ]
Run Code Online (Sandbox Code Playgroud)

这是所需的输出:

['text_with_Luis_to_variables_12344',
 'text_with_Luis_to_variables_553454',
 'text_with_Luis_to_variables_dadada']
Run Code Online (Sandbox Code Playgroud)

但是使用.format而不是.replace.

python string string-formatting

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

如何将图像导入谷歌colab

我开始使用谷歌colab我想要从我的笔记本电脑加载一组图像进行处理.

我试过这个:

在此输入图像描述

但我得到错误:

TypeError: embedded NUL character
Run Code Online (Sandbox Code Playgroud)

那么哪个是导入图像的正确过程?

python python-imaging-library google-colaboratory

4
推荐指数
2
解决办法
7350
查看次数

将scrapy项目导出到不同的文件

我是从moocs刮审查喜欢这一个

从那里我获得了所有课程的详细信息,每个评论本身有 5 个项目和另外 6 个项目。

这是我拥有的课程详细信息的代码:

def parse_reviews(self, response):
    l = ItemLoader(item=MoocsItem(), response=response)
    l.add_xpath('course_title', '//*[@class="course-header-ng__main-info__name__title"]//text()')
    l.add_xpath('course_description', '//*[@class="course-info__description"]//p/text()')
    l.add_xpath('course_instructors', '//*[@class="course-info__instructors__names"]//text()')
    l.add_xpath('course_key_concepts', '//*[@class="key-concepts__labels"]//text()')
    l.add_value('course_link', response.url)
    return l.load_item()
Run Code Online (Sandbox Code Playgroud)

现在我想包括评论详细信息,每个评论另外 5 个项目。由于课程数据对于所有评论都是通用的,我想将其存储在不同的文件中,然后使用课程名称/ID 关联数据。

这是我用于评论项目的代码:

for review in response.xpath('//*[@class="review-body"]'):
    review_body = review.xpath('.//div[@class="review-body__content"]//text()').extract()
    course_stage =  review.xpath('.//*[@class="review-body-info__course-stage--completed"]//text()').extract()
    user_name =  review.xpath('.//*[@class="review-body__username"]//text()').extract()
    review_date =  review.xpath('.//*[@itemprop="datePublished"]/@datetime').extract()
    score =  review.xpath('.//*[@class="sr-only"]//text()').extract()
Run Code Online (Sandbox Code Playgroud)

我尝试使用临时解决方案,返回每个案例的所有项目,但也不起作用:

def parse_reviews(self, response):
    #print response.body
    l = ItemLoader(item=MoocsItem(), response=response)
    #l = MyItemLoader(selector=response)
    l.add_xpath('course_title', '//*[@class="course-header-ng__main-info__name__title"]//text()')
    l.add_xpath('course_description', '//*[@class="course-info__description"]//p/text()')
    l.add_xpath('course_instructors', '//*[@class="course-info__instructors__names"]//text()')
    l.add_xpath('course_key_concepts', '//*[@class="key-concepts__labels"]//text()')
    l.add_value('course_link', response.url)

    for review in response.xpath('//*[@class="review-body"]'):
        l.add_xpath('review_body', './/div[@class="review-body__content"]//text()') …
Run Code Online (Sandbox Code Playgroud)

python scrapy scrapy-pipeline

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

Docker 上的 Flask 应用程序:URL 超出最大重试次数

我正在开发一个简单的 Flask 应用程序,我使用默认模板:

from flask import render_template
import connexion

# Create the application instance
app = connexion.App(__name__, specification_dir="./")

# read the swagger.yml file to configure the endpoints
app.add_api("swagger.yml")


# Create a URL route in our application for "/"
@app.route("/")
def home():
    """
    This function just responds to the browser URL
    localhost:5000/

    :return:        the rendered template "home.html"
    """
    return render_template("home.html")


if __name__ == "__main__":
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

我只是调用一个返回并返回“ok”响应的虚拟函数:

def test(features):
    return 'ok'
Run Code Online (Sandbox Code Playgroud)

当我使用以下代码直接在我的机器上调用它时:

headers = {'content-type': 'application/json'}
#url = "http://localhost:5000/api/document"

url = "http://localhost:5000/api/scraping" …
Run Code Online (Sandbox Code Playgroud)

python api flask docker

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

在线性回归上使用PCA

我想在应用线性回归之前使用主成分分析来减少一些噪声.

我有1000个样本和200个功能

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA

X = np.random.rand(1000,200)
y = np.random.rand(1000,1)
Run Code Online (Sandbox Code Playgroud)

有了这些数据,我可以训练我的模型:

model.fit(X,y)
Run Code Online (Sandbox Code Playgroud)

但如果我在申请PCA后尝试相同的话

pca = PCA(n_components=8)
pca.fit(X)
PCA(copy=True, iterated_power='auto', n_components=3, random_state=None,
  svd_solver='auto', tol=0.0, whiten=False)
principal_components =  pca.components_

model.fit(principal_components,y)
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

ValueError: Found input variables with inconsistent numbers of samples: [8, 1000]
Run Code Online (Sandbox Code Playgroud)

python machine-learning pca scikit-learn

3
推荐指数
1
解决办法
6178
查看次数