相关疑难解决方法(0)

读取excel文件时的Pandas数据帧和字符编码

我正在阅读一个包含多个数字和分类数据的excel文件.name_string列包含外语字符.当我尝试查看name_string列的内容时,我得到了我想要的结果,但外部字符(在Excel电子表格中正确显示)显示的编码错误.这是我有的:

import pandas as pd
df = pd.read_excel('MC_simulation.xlsx', 'DataSet', encoding='utf-8')
name_string = df.name_string.unique()
name_string.sort()
name_string
Run Code Online (Sandbox Code Playgroud)

产生以下内容:

array([u'4th of July', u'911', u'Abab', u'Abass', u'Abcar', u'Abced',
       u'Ceded', u'Cedes', u'Cedfus', u'Ceding', u'Cedtim', u'Cedtol',
       u'Cedxer', u'Chevrolet Corvette', u'Chuck Norris',
       u'Cristina Fern\xe1ndez de Kirchner'], dtype=object)
Run Code Online (Sandbox Code Playgroud)

在最后一行,正确编码的名称应该是CristinaFernándezdeKirchner.有人可以帮我解决这个问题吗?

python excel character-encoding pandas

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

Python中的字符串对象

我有一些数据对象,我想在其上实现一个字符串和等于深入的函数.

我实现了streq,虽然平等工作正常但我不能以同样的方式使str行为:

class Bean(object):

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

    def __str__(self):
        return str(self.__dict__)

    def __eq__(self, other):
        return self.__dict__ == other.__dict__
Run Code Online (Sandbox Code Playgroud)

当我跑:

t1 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)])
t2 = Bean("bean 1", [Bean("bean 1.1", "same"), Bean("bean 1.2", 42)])
t3 = Bean("bean 1", [Bean("bean 1.1", "different"), Bean("bean 1.2", 42)])

print(t1)
print(t2)
print(t3)
print(t1 == t2)
print(t1 == t3)
Run Code Online (Sandbox Code Playgroud)

我明白了:

{'attr2': [<__main__.Bean object at 0x7fc092030f28>, <__main__.Bean object at …
Run Code Online (Sandbox Code Playgroud)

python tostring python-3.x

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

如何将这种类型的数据<hdf5对象引用>转换为python中更具可读性的东西?

我有很大的数据集.所有信息都存储在hdf5格式文件中.我找到了python的h5py库.一切都正常,除了

[<HDF5 object reference>]
Run Code Online (Sandbox Code Playgroud)

我不知道如何将它转换为更具可读性的东西.我可以这样做吗?因为这个问题的文档对我来说有点困难.也许还有其他一些不同语言的解决方案,不仅仅是Python.我很感激我将得到的每一个帮助.

在理想中它应该链接到文件.

这是我的代码的一部分:

import numpy as np
import h5py 
import time

f = h5py.File('myfile1.mat','r') 
#print f.keys()
test = f['db/path']
st = test[3]
print(  st )
Run Code Online (Sandbox Code Playgroud)

st 输出是 [<HDF5 object reference>]

test 输出是 <HDF5 dataset "path": shape (73583, 1), type "|O8">

而且我期待的 [<HDF5 object reference>]是那样的东西:/home/directory/file1.jpg.如果有可能的话.

python hdf5 python-2.7 h5py

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

如何将字典记录到日志文件中?

我有一本字典:

 d = {name : "John", age: 10}. 
Run Code Online (Sandbox Code Playgroud)

并将日志文件设置为:

logging.basicConfig(level = logging.DEBUG, filename = "sample.log")
Run Code Online (Sandbox Code Playgroud)

是否可以将此字典记录到"sample.log"文件中?如果是,我该怎么办?

python logging python-2.7

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

python print vs __str__?

任何人都可以启发我print sth和之间的差异print str(sth)

例如,在sqlite3官方文档的示例中,当前可以看到以下代码创建数据库,然后使用工厂类来包装从那里提取的数据:

(1)创建数据库:

# I am using CPython 2.7, but I suppose 2.6 will be Ok as well
import sqlite3
conn = sqlite3.connect(":memory:")
c = conn.cursor()

c.execute('''create table stocks
(date text, trans text, symbol text, qty real, price real)''')
c.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")
conn.commit()

c.close()
Run Code Online (Sandbox Code Playgroud)

(2)现在使用Row工厂生产一些物体:

>>> conn.row_factory = sqlite3.Row
>>> c = conn.cursor()

>>> c.execute('select * from stocks')
<sqlite3.Cursor object at 0x7f4e7dd8fa80>
>>> r = c.fetchone()
>>> type(r) …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

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

Python:打印自定义异常时超出了最大递归深度

以下代码抛出RuntimeError: maximum recursion depth exceeded while getting the str of an object.我可以用两种不同的方式解决无限递归,但我不明白为什么每种修复都有效,因此不知道使用哪种,或者两种方法是否正确.

class FileError( Exception ):
    def __init__( self, filename=None, *a, **k ):
        #Fix 1: remove super
        super( FileError, self ).__init__( self, *a, **k )
        self.filename = filename
    def __repr__( self ):
        return "<{0} ({1})>".format( self.__class__.__name__, self.filename )
    #Fix 2: explicitly define __str__
    #__str__ = __repr__

print( FileError( "abc" ) )
Run Code Online (Sandbox Code Playgroud)

如果我删除super,代码运行但不打印任何东西.这没有意义,因为根据这篇文章,Python中的__str__和__repr__之间的区别,省略__str__将调用,__repr__但这似乎不会发生在这里.

相反,如果我继续调用super并添加__str__ = __repr__,那么我得到预期的输出并且没有递归.

有人可以解释为什么无限递归存在,为什么每次更改都会解决inifinte递归,以及为什么一个修复可能比另一个更优先?

python recursion repr custom-exceptions

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

__str__和__repr__之间的区别?

我写这段代码:

class Item:
    def __init__(self, name):
        self._name = name;
    def __str__(self):
        return "Item: %s" % self._name
Run Code Online (Sandbox Code Playgroud)

我跑的时候

print((Item("Car"),))
Run Code Online (Sandbox Code Playgroud)

输出是

(<__main__.Item object at 0x0000000002D32400>,)
Run Code Online (Sandbox Code Playgroud)

当我将代码更改为:

class Item:
    def __init__(self, name):
        self._name = name;
    def __repr__(self):
        return "Item: %s" % self._name
    def __str__(self):
        return "Item: %s" % self._name
Run Code Online (Sandbox Code Playgroud)

然后输出

(Item: Car,)
Run Code Online (Sandbox Code Playgroud)

所以,现在我感到困惑的区别__repr____str__.

python

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

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

如何将字符串转换回列表

我有一个清单:

ab = [1, 2, a, b, c]
Run Code Online (Sandbox Code Playgroud)

我做了:

strab = str(ab).
Run Code Online (Sandbox Code Playgroud)

所以strab现在是一个字符串.

我想将该字符串转换回列表.

我怎样才能做到这一点?

python string casting list

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

Python:用反斜杠连接元组

我尝试使用 .join 方法连接两个字符串的元组,如下所示。

>>> my_tuple = ("parent", "child")
>>> "\\".join(my_tuple)
Run Code Online (Sandbox Code Playgroud)

我希望它会回来parent\child,然而,它又回来了parent\\child

为什么是这样?如果我尝试简单地打印它,则用另一个反斜杠转义反斜杠效果很好。

>>> print "parent\\child"
>>> parent\child
Run Code Online (Sandbox Code Playgroud)

在 Windows 7 上的 Python 2.7.3 中观察到。

python join tuples backslash

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