Python 3.x 为什么列类型可以';t在转换器中读取';什么背景?

Python 3.x 为什么列类型可以';t在转换器中读取';什么背景?,python-3.x,pandas,csv,dataframe,converters,Python 3.x,Pandas,Csv,Dataframe,Converters,我想读取指定列的字符串类型的csv文件,数据文件位于: 请下载并保存为$HOME\cbond.csv(由于GFW原因,无法上传到dropbox和其他网络磁盘,建国云提供英文gui,创建您自己的免费帐户并下载我的示例数据文件) 我创建了正股代码在csv文件中作为字符串类型使用转换器,使用df.info()检查所有列的数据类型 而不是 正股代码 239 non-null string ? 升级熊猫: sudo apt-get install --upgrade python3

我想读取指定列的字符串类型的csv文件,数据文件位于:

请下载并保存为
$HOME\cbond.csv
(由于GFW原因,无法上传到dropbox和其他网络磁盘,建国云提供英文gui,创建您自己的免费帐户并下载我的示例数据文件)

我创建了
正股代码在csv文件中作为字符串类型使用转换器,使用
df.info()
检查所有列的数据类型

而不是

   正股代码     239 non-null string  
?

升级熊猫:

sudo apt-get install --upgrade  python3-pandas
Reading package lists... Done
Building dependency tree       
Reading state information... Done
python3-pandas is already the newest version (0.19.2-5.1).
尝试不同的语句:

>>> import pandas as pd
>>> pd.__version__
'0.24.2'
>>> test_1  = pd.read_csv('cbond.csv',dtype={'正股代码':'string'})
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/dtypes/common.py", line 2011, in pandas_dtype
    npdtype = np.dtype(dtype)
TypeError: data type "string" not understood

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py", line 702, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py", line 429, in _read
    parser = TextFileReader(filepath_or_buffer, **kwds)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py", line 895, in __init__
    self._make_engine(self.engine)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py", line 1122, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py", line 1853, in __init__
    self._reader = parsers.TextReader(src, **kwds)
  File "pandas/_libs/parsers.pyx", line 490, in pandas._libs.parsers.TextReader.__cinit__
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/dtypes/common.py", line 2017, in pandas_dtype
    dtype))
TypeError: data type 'string' not understood
>>> test_2  = pd.read_csv('cbond.csv',dtype={'正股代码':'str'})
>>> test_2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 239 entries, 0 to 238
Data columns (total 17 columns):
代码       239 non-null int64
转债名称     239 non-null object
现价       239 non-null float64
涨跌幅      239 non-null float64
正股代码     239 non-null object
正股名称     239 non-null object
正股价      239 non-null float64
正股涨跌     239 non-null float64
转股价      239 non-null float64
回售触发价    239 non-null float64
强赎触发价    239 non-null float64
到期时间     239 non-null object
剩余年限     239 non-null float64
转股起始日    239 non-null object
发行规模     239 non-null float64
剩余规模     239 non-null object
转股溢价率    239 non-null float64
dtypes: float64(10), int64(1), object(6)
memory usage: 31.8+ KB
>>将熊猫作为pd导入
>>>pd.\u版本__
'0.24.2'
>>>test_1=pd.read_csv('cbond.csv',dtype={'正股代码':'字符串“})
回溯(最近一次呼叫最后一次):
文件“/usr/local/lib/python3.5/dist packages/pandas/core/dtypes/common.py”,第2011行,在pandas\u dtype中
npdtype=np.dtype(dtype)
TypeError:未理解数据类型“字符串”
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
parser\u f中的文件“/usr/local/lib/python3.5/dist packages/pandas/io/parsers.py”,第702行
返回读取(文件路径或缓冲区,kwds)
文件“/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py”,第429行,已读
parser=TextFileReader(文件路径或缓冲区,**kwds)
文件“/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py”,第895行,在__
自制发动机(自制发动机)
文件“/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py”,第1122行,在引擎中
self.\u engine=CParserWrapper(self.f,**self.options)
文件“/usr/local/lib/python3.5/dist-packages/pandas/io/parsers.py”,第1853行,在__
self.\u reader=parsers.TextReader(src,**kwds)
文件“pandas/_libs/parsers.pyx”,第490行,在pandas._libs.parsers.TextReader.\uu\cinit中__
文件“/usr/local/lib/python3.5/dist packages/pandas/core/dtypes/common.py”,第2017行,在pandas\u dtype中
数据类型)
TypeError:无法理解数据类型“字符串”
>>>test_2=pd.read_csv('cbond.csv',dtype={'正股代码':'str'})
>>>测试_2.info()
范围索引:239个条目,0到238
数据列(共17列):
代码       239非空int64
转债名称     239非空对象
现价       239非空浮点64
涨跌幅      239非空浮点64
正股代码     239非空对象
正股名称     239非空对象
正股价      239非空浮点64
正股涨跌     239非空浮点64
转股价      239非空浮点64
回售触发价    239非空浮点64
强赎触发价    239非空浮点64
到期时间     239非空对象
剩余年限     239非空浮点64
转股起始日    239非空对象
发行规模     239非空浮点64
剩余规模     239非空对象
转股溢价率    239非空浮点64
数据类型:float64(10)、int64(1)、object(6)
内存使用率:31.8+KB

读取csv文件后分配列的数据类型是否有帮助

df['正股代码'] = df['正股代码'].astype('string')
在新的pandas 1.0中,字符串数据类型正在试验中。 请在此处阅读更多信息:

这对我很有用:

test_df = pd.DataFrame(data={'numbers_column':np.nan,
                        'strings_column':['3_re', '4_re', '5_re','random_str']},
                  index=[1,2,3, 4])

## until here the dtype of strings_column is still object

test_df['strings_column'] = test_df['strings_column'].astype('string')
 test_2 = pd.read_csv(.....,
                dtype={'正股代码':'string'})
或者在打开文件时立即将其作为字符串读取,这对我很有用:

test_df = pd.DataFrame(data={'numbers_column':np.nan,
                        'strings_column':['3_re', '4_re', '5_re','random_str']},
                  index=[1,2,3, 4])

## until here the dtype of strings_column is still object

test_df['strings_column'] = test_df['strings_column'].astype('string')
 test_2 = pd.read_csv(.....,
                dtype={'正股代码':'string'})

1.0.0
之前,即您的版本
0.19
, 熊猫中没有
dtype
string
,可以是内部
np.str
StringArray
来自
numpy
。 哪个
df.info()
视为对象
dtype


使用要求Pandas>=1.0.2的
转换数据类型,它支持使用支持
pd.NA的数据类型将列转换为最佳数据类型

文件:

试试这个:


作为pd进口熊猫
df=pd.read\u csv('cbond.csv')
dfn=df.convert\u dtypes()
打印(dfn)
"""
代码         Int64
转债名称      一串
现价       浮动64
涨跌幅      浮动64
正股名称      一串
正股价      浮动64
正股涨跌     浮动64
转股价      浮动64
回售触发价    浮动64
强赎触发价    浮动64
到期时间      一串
剩余年限     浮动64
正股代码       Int64
转股起始日     一串
发行规模     浮动64
剩余规模      一串
转股溢价率    浮动64
数据类型:对象
"""
此外,为什么
df=pd.read_csv('cbond.csv',sep=',',header=0,converters={'正股代码':str})
df['正股代码'] = df['正股代码'].astype('string')
不能按我们的要求工作吗

这对我/我们来说似乎是一个bug,但对熊猫来说却是一个特性


不管怎样,
convert\u dtypes
已经为我解决了这个问题。

可能与那篇文章完全不同,我的问题集中在参数
converter
,而不是df['fieldname']。astype(str)。在read_csv@it_is_a_文学中指定编码,不确定这是否是您想要的方式,但可以这样做:
df=pd.read_csv(“cbond.csv”,sep=”,“,header=0,dtype={”正股代码':'字符串“})
Use latest pandas,字符串类型不在早期版本的pandas中,无法使用
df=pd.read_csv(“cbond.csv”,sep=',,header=0,dtype={”正股代码':'str'})
您不清楚哪一部分?您是否尝试按如下方式读取您的csv:df=pd.read_csv('cbond.csv',sep=',',',,header=0,dtype={'正股代码':字符串“})数据类型字符串自2020年1月底起仅在pandas 1.0中可用。在早期版本的pandas中,您无法将列另存为数据类型字符串。如果更新pandas有帮助,请告知我
 test_2 = pd.read_csv(.....,
                dtype={'正股代码':'string'})