小编mau*_*bio的帖子

pandas:如何将数据框的所有数字列转换为对数

在 RI 中,可以对数据框的所有数字列应用对数(或平方根等)变换,方法是:

logdf <- log10(df)
Run Code Online (Sandbox Code Playgroud)

Python/Pandas 中是否有等价的东西?我看到有一个“转换”和一个(类似 R 的)“应用”函数,但在这种情况下无法弄清楚如何使用它们。

感谢您的任何提示或建议。

python pandas

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

QListView 中的复选框选择

我开发了一个带有复选框的简单对话框,它允许用户从列表中选择一个或多个项目。除了标准的“确定”和“取消”按钮之外,它还添加了“全选”和“取消全选”按钮,允许用户一次选中/取消选中所有项目(这对于大型列表很方便)。

import os, sys
from PyQt4 import Qt, QtCore, QtGui

class ChecklistDialog(QtGui.QDialog):
    def __init__(self, name, stringlist=None, checked=False, icon=None, parent=None):
        super(ChecklistDialog, self).__init__(parent)

        self.name = name
        self.icon = icon
        self.model = QtGui.QStandardItemModel()
        self.listView = QtGui.QListView()

        if stringlist is not None:
            for i in range(len(stringlist)):
                item = QtGui.QStandardItem(stringlist[i])
                item.setCheckable(True)
                check = QtCore.Qt.Checked if checked else QtCore.Qt.Unchecked
                item.setCheckState(check)
                self.model.appendRow(item)

        self.listView.setModel(self.model)

        self.okButton = QtGui.QPushButton("OK")
        self.cancelButton = QtGui.QPushButton("Cancel")
        self.selectButton = QtGui.QPushButton("Select All")
        self.unselectButton = QtGui.QPushButton("Unselect All")

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(self.okButton)
        hbox.addWidget(self.cancelButton)
        hbox.addWidget(self.selectButton)
        hbox.addWidget(self.unselectButton)

        vbox = …
Run Code Online (Sandbox Code Playgroud)

python pyqt pyqt4 qlistview qcheckbox

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

将电子表格的列存储在Python字典中

我有一个存储在Excel文件中的表,如下所示:

Species     Garden Hedgerow Parkland Pasture Woodland
Blackbird       47       10      40        2        2
Chaffinch       19        3       5        0        2
Great Tit       50        0      10        7        0
House Sparrow   46       16       8        4        0
Robin            9        3       0        0        2
Song Thrush      4        0       6        0        0

我正在使用xlrdPython库来读取这些数据.我将它读入列表列表(将表的每一行存储为列表)没有问题,使用下面的代码:

from xlrd import open_workbook
wb = open_workbook("Sample.xls")
headers = []
sdata = []
for s in wb.sheets():
    print "Sheet:",s.name
    if s.name.capitalize() == "Data":
        for row in range(s.nrows):
            values = []
            for …
Run Code Online (Sandbox Code Playgroud)

python excel dictionary xlrd

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

使用PyInstaller使用PyQt4 + Matplotlib冻结Python应用程序

在尝试使用PyInstaller(v2.1)"冻结"在Windows XP SP3下使用PyQt4(v4.10.4)和Matplotlib(v1.4.2)的Python(v2.78)应用程序时,我遇到了一个恼人的问题.

在我的计划的最开始,我有以下几行:

import matplotlib
matplotlib.use("Qt4Agg")
matplotlib.rcParams["backend.qt4"] = "PyQt4"
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
Run Code Online (Sandbox Code Playgroud)

当我使用该行运行PyInstaller时:

pyinstaller --noconsole --icon=app.ico App.py
Run Code Online (Sandbox Code Playgroud)

应用程序被正确冻结到"dist"文件夹中,它运行没有任何麻烦.问题是,分发文件夹中包含了许多不需要的文件!通过这些"不需要的"文件,我指的是几个对我的应用程序显然无用的"wx"模块(因为它使用Qt而不是Wx用于UI).如果我从dist文件夹手动删除这些文件,该应用程序仍然运行良好.

所以,我的一个大问题是:在使用PyInstaller冻结应用程序时,如何摆脱这些不需要的文件?

我能找到的与py2exe和cx_Freeze,但没有什么是指PyInstaller类似问题的几种可能的解决方案(而这些是我的首选"编译",因为它一直是唯一跨平台的一个似乎Windows和Linux下工作得很好) .

在此先感谢您提供的任何帮助!

编辑:此外,运行PyInstaller时,我收到一条丑陋的错误消息:

43592 INFO: Processing hook hook-matplotlib
Traceback (most recent call last):
  File "<string>", line 3, in <module>
  File "C:\Python27\lib\site-packages\matplotlib\backends\backend_webagg.py", li
ne 30, in <module>
    raise RuntimeError("The WebAgg backend requires Tornado.")
RuntimeError: The WebAgg backend requires Tornado.
Run Code Online (Sandbox Code Playgroud)

但当然我没有使用任何WebAgg后端(并且不知道到底是什么"龙卷风"!).

在冻结过程结束时,我收到了警告:

265046 WARNING: lib not found: gdiplus.dll dependency of C:\Python27\lib\site-pa
ckages\wx-2.8-msw-unicode\wx\wxmsw28u_core_vc.dll
Run Code Online (Sandbox Code Playgroud)

我也希望在冻结过程中消除这两个消息(我认为我将会解决掉掉不需要的后端的问题)!

"

python qt matplotlib pyinstaller

6
推荐指数
0
解决办法
888
查看次数

使用Python lxml处理嵌套元素

鉴于以下简单的XML数据:

<book>
   <title>My First Book</title>
   <abstract>
         <para>First paragraph of the abstract</para>
         <para>Second paragraph of the abstract</para>
    </abstract>
    <keywordSet>
         <keyword>First keyword</keyword>
         <keyword>Second keyword</keyword>
         <keyword>Third keyword</keyword>
    </keywordSet>
</book>
Run Code Online (Sandbox Code Playgroud)

如何使用lxml遍历树,并获取"abstract"元素中的所有段落,以及"keywordSet"元素中的所有关键字?

下面的代码片段仅返回每个元素中的第一行文本:

from lxml import objectify
root = objectify.fromstring(xml_string) # xml_string contains the XML data above
print root.title # returns the book title
for line in root.abstract:
    print line.para # returns only yhe first paragraph
for word in root.keywordSet:
    print word.keyword # returns only the first keyword in the set
Run Code Online (Sandbox Code Playgroud)

我试图按照这个例子 …

python xml lxml

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

在Windows XP上安装scikit-bio时遇到问题

当尝试使用Python 2.78和Visual C++ 2008 Express Edition在Windows XP上通过pip安装scikit-bio工具包时,该过程被VC发出以下消息中断:

cl : Command line error D8021 : invalid numeric argument '/Wno-error=declaration
-after-statement' 
Run Code Online (Sandbox Code Playgroud)

关于此错误,Microsoft Developer Network网站只是说:

invalid numeric argument 'number'

A number greater than 65,534 was specified as a numeric argument.
Run Code Online (Sandbox Code Playgroud)

我还没有尝试在Linux下安装scikit-bio(Ubuntu 12.04 Precise),但我的印象是它能正常工作(就像Linux一样).

有没有人成功在Windows下安装scikit-bio(XP,7,8)?任何提示?

提前致谢!

c++ python windows scikits skbio

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

Python 从包含多个地标的 KML 文件中提取数据

我有一个 KML 文件,如下所示:

<?xml version="1.0"?><kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>MST =T</name>
<description><![CDATA[<p>KML test file</p>
<p>This is a test version.</p>]]></description>
<Style id="spstyle5">
    <IconStyle>
        <color>ff3EE23E</color>
        <Icon><href>http://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href></Icon>
    </IconStyle>
    <LineStyle>
        <color>ff3EE23E</color>
        <width>4</width>
    </LineStyle>
</Style>
<Folder>
    <name>Track5</name>
    <visibility>0</visibility>
            <name>sp5_sp6_ Track</name>
            <description><![CDATA[<i>sp5_sp6_</i> track<br>pantrack id:5]]></description>
            <Placemark>
                <name>sp5_sp6_ MST</name>
                <description><![CDATA[<i> species sp5_sp6_</i> mst<br>long= 648.000 corte 0.250000]]></description>
                <styleUrl>#spstyle5</styleUrl>
                <MultiGeometry>
            <LineString>
                        <tessellate>true</tessellate>
                        <altitudeMode>clampToGround</altitudeMode>
                        <coordinates>
                            8.000,8.000 6.000,7.000
                        </coordinates>
                    </LineString>
            <LineString>
                        <tessellate>true</tessellate>
                        <altitudeMode>clampToGround</altitudeMode>
                        <coordinates>
                            5.000,7.000 6.000,7.000
                        </coordinates>
                    </LineString>
            <LineString>
                        <tessellate>true</tessellate>
                        <altitudeMode>clampToGround</altitudeMode>
                        <coordinates>
                            3.000,8.000 5.000,7.000
                        </coordinates>
                    </LineString>
            <LineString>
                        <tessellate>true</tessellate>
                        <altitudeMode>clampToGround</altitudeMode>
                        <coordinates>
                            2.000,8.000 3.000,8.000
                        </coordinates>
                    </LineString> …
Run Code Online (Sandbox Code Playgroud)

python kml

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

使用Python和BeautifulSoup解析Google Scholar结果

在Google学术搜索中进行典型的关键字搜索(请参见屏幕截图)后,我想获得一个字典,其中包含出现在页面上的每个出版物的标题网址(例如results = {'title': 'Cytosolic calcium regulates ion channels in the plasma membrane of Vicia faba guard cells', 'url': 'https://www.nature.com/articles/338427a0'}。

在此处输入图片说明

要从Google学术搜索检索结果页面,我使用以下代码:

from urllib import FancyURLopener, quote_plus
from bs4 import BeautifulSoup

class AppURLOpener(FancyURLopener):
    version = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36'

openurl = AppURLOpener().open
query = "Vicia faba"
url = 'https://scholar.google.com/scholar?q=' + quote_plus(query) + '&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search'
#print url
content = openurl(url).read()
page = BeautifulSoup(content, 'lxml')
print page
Run Code Online (Sandbox Code Playgroud)

此代码以(非常难看的)HTML格式正确返回结果页面。但是,由于无法确定如何使用BeautifulSoup(我不太熟悉)来解析结果页面并检索数据,因此我无法继续前进。

请注意,问题在于解析和从结果页面提取数据,而不是Google Scholar本身,因为上面的代码可以正确检索结果页面。 …

python beautifulsoup google-scholar

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

如何在 Qt/PyQt/PySide 网格布局中控制小部件的大小

我被一个愚蠢但令人讨厌的问题震惊了。我想为网格布局上的两个列表小部件设置不同的大小,一个在另一个之上。因此,我想将 60% 的表单空间设置为上部小部件,将 40% 设置为下部小部件。我尝试使用 setRowStretch,但没有成功。

这是我的代码:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

def window():
    app = QApplication(sys.argv)
    win = QWidget()

    list1 = QListView()
    list2 = QListView()

    grid = QGridLayout()
    grid.setRowStretch(6, 4)
    grid.addWidget(list1)
    grid.setSpacing(2)
    grid.addWidget(list2)

    win.setLayout(grid)
    win.setGeometry(300, 150, 350, 300)
    win.setWindowTitle("Example")
    win.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
   window()
Run Code Online (Sandbox Code Playgroud)

感谢您提供的任何帮助。

python pyqt pyqt4

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

Python NetworkX从关联矩阵创建图形

我有一个关联矩阵(其中行是节点,列是边),如下所示(从文本文件读取到NumPy数组):

[[1 1 1 1 1 1 1 1 1 1]
 [1 1 1 1 1 1 1 0 0 0]
 [1 1 1 1 1 0 1 1 0 0]
 [0 0 1 1 1 0 1 0 0 0]
 [1 1 1 1 1 1 0 0 0 0]
 [1 1 0 1 1 0 0 0 0 0]
 [1 0 1 0 0 1 0 1 0 0]
 [0 1 0 1 1 0 0 0 0 …
Run Code Online (Sandbox Code Playgroud)

python networkx

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

Python Regex在点或逗号后添加空格

我有一个字符串如下:

line ="这是一个文本.这是另一个文本,逗号后面没有空格."

我想在点逗号之后添加一个空格,以便最终结果是:

newline ="这是一个文本.这是另一个文本,逗号后面没有空格."

我从这里尝试了解决方案:Python Regex在点后添加空格,但它仅适用于点逗号.我无法掌握如何让正则表达式同时识别这两个字符.

python regex

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

Python - 从字符串创建集合

我有格式的字符串,"1-3 6:10-11 7-9"从中我想创建数字集,如下所示{1,2,3,6,10,11,7,8,9}.

要从数字范围创建集合,我有以下代码:

def create_set(src):
    lset = []
    if len(src) > 0:
        pos = src.find('-')
        if pos != -1:
            first = int(src[:pos])
            last  = int(src[pos+1:])
        else:
            return [int(src)]  # Only one number
        for j in range (first, last+1): 
            lset.append(j)
        return set(lset)
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚当它出现在字符串中时如何正确处理':'.有人能帮我吗?

提前致谢!

编辑:顺便说一句,有没有一种更简洁的方法来解析这样的字符串,也许使用正则表达式?

python set

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

python - 如何从CSV字符串创建一个dctionary

我有一些逗号分隔的字符串如下:

filename1,12345,ABC
filename2,6789,CDE
filename3,999,GHI
...
etc.
Run Code Online (Sandbox Code Playgroud)

我想从这些数据构建一个字典,使用第一列(文件名)作为键,其余数据作为属性列表(可能是大小,最后访问日期等),如

{'filename1': ['12345','ABC'], 'filename2': ['6789','CDE'], 'filename3':['999','GHI']}
Run Code Online (Sandbox Code Playgroud)

数据包括标题行,每行是一个内置代码的csv-string,而不是从文件中读取.

我试过这样的事情:

import csv

s = """
filename1,12345,ABC
filename2,6789,CDE
filename3,999,GHI
"""

reader_list = csv.DictReader(s.splitlines())
for row in reader_list:
    print row
Run Code Online (Sandbox Code Playgroud)

返回这个:

{None: ['filename1', '12345', 'ABC']}
{None: ['filename2', '6789', 'CDE']}
{None: ['filename3', '999', 'GHI']}
Run Code Online (Sandbox Code Playgroud)

但我想不出用文件名创建密钥的方法.

任何提示?

python csv

0
推荐指数
1
解决办法
52
查看次数