本文的目的是介绍熊猫read_csvdtype读取所有列,但很少读取为字符串的详细情况,特别关注panda读取csv文件的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了
本文的目的是介绍熊猫read_csv dtype读取所有列,但很少读取为字符串的详细情况,特别关注panda读取csv文件的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解熊猫read_csv dtype读取所有列,但很少读取为字符串的机会,同时也不会遗漏关于Kaggle 的 Csv 将所有列放入 1 - 如何与 pd.read_csv 分开并使 df 可用、numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32、pandas read_csv dtype前导零、Pandas read_csv low_memory 和 dtype 选项的知识。
本文目录一览:- 熊猫read_csv dtype读取所有列,但很少读取为字符串(panda读取csv文件)
- Kaggle 的 Csv 将所有列放入 1 - 如何与 pd.read_csv 分开并使 df 可用
- numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32
- pandas read_csv dtype前导零
- Pandas read_csv low_memory 和 dtype 选项
熊猫read_csv dtype读取所有列,但很少读取为字符串(panda读取csv文件)
我正在使用Pandas读取一堆CSV。将选项json传递给dtype参数,以告诉pandas将哪些列读取为字符串而不是默认值:
dtype_dic= { ''service_id'':str, ''end_date'':str, ... }feedArray = pd.read_csv(feedfile , dtype = dtype_dic)
在我的场景中,除少数特定列外, 所有 列均应读取为字符串。因此,与其将几列定义为str indtype_dic
,不如将我选择的几列设置为int或float。有没有办法做到这一点?
这是循环遍历具有不同列的各种CSV的循环,因此在将整个csv读取为字符串(dtype=str
)后进行直接列转换将不容易,因为我不会立即知道csv包含哪些列。(我宁愿花精力在dtype
json中定义所有列!)
编辑:但是,如果有一种方法可以处理要转换为数字的列名列表,而不会错误地指出该列不在该csv中,那么是的,如果没有其他方法可以解决这个问题这是在csv阅读阶段本身。
答案1
小编典典编辑-对不起,我误读了你的问题。更新了我的答案。
您可以将整个csv读取为字符串,然后将所需的列转换为其他类型,如下所示:
df = pd.read_csv(''/path/to/file.csv'', dtype=str)# example df; yours will be from pd.read_csv() abovedf = pd.DataFrame({''A'': [''1'', ''3'', ''5''], ''B'': [''2'', ''4'', ''6''], ''C'': [''x'', ''y'', ''z'']})types_dict = {''A'': int, ''B'': float}for col, col_type in types_dict.items(): df[col] = df[col].astype(col_type)
另一种方法是,如果您确实要在读入文件时为所有列指定正确的类型,而不是在以后更改它们:仅读入列名(无行),然后使用那些来填充应为字符串的列
col_names = pd.read_csv(''file.csv'', nrows=0).columnstypes_dict = {''A'': int, ''B'': float}types_dict.update({col: str for col in col_names if col not in types_dict})pd.read_csv(''file.csv'', dtype=types_dict)
Kaggle 的 Csv 将所有列放入 1 - 如何与 pd.read_csv 分开并使 df 可用
如何解决Kaggle 的 Csv 将所有列放入 1 - 如何与 pd.read_csv 分开并使 df 可用?
我刚刚从 kaggle 下载了这个 CSV
https://www.kaggle.com/psvishnu/bank-direct-marketing?select=bank-full.csv
然而,当它下载时,所有17列左右都在1中,所以当我使用
df = pd.read_csv(''bank-full.csv)
它也在一列中包含所有值。
任何想法都会很棒,我以前从未遇到过这个问题,谢谢!
df 示例
58;"management";"married";"tertiary";"no";2143;"yes";"no";"unkNown";5;"may";261;1;-1;0;"unkNown";"no"
0 44;"technician";"single";"secondary";"no";29;"yes";"no";"unkNown";5;"may";151;1;-1;0;"unkNown";"no"
1 33;"entrepreneur";"married";"secondary";"no";2;"yes";"yes";"unkNown";5;"may";76;1;-1;0;"unkNown";"no"
2 47;"blue-collar";"married";"unkNown";"no";1506;"yes";"no";"unkNown";5;"may";92;1;-1;0;"unkNown";"no"
3 33;"unkNown";"single";"unkNown";"no";1;"no";"no";"unkNown";5;"may";198;1;-1;0;"unkNown";"no"
4 35;"management";"married";"tertiary";"no";231;"yes";"no";"unkNown";5;"may";139;1;-1;0;"unkNown";"no"
5 28;"management";"single";"tertiary";"no";447;"yes";"yes";"unkNown";5;"may";217;1;-1;0;"unkNown";"no"
6 42;"entrepreneur";"divorced";"tertiary";"yes";2;"yes";"no";"unkNown";5;"may";380;1;-1;0;"unkNown";"no"
7 58;"retired";"married";"primary";"no";121;"yes";"no";"unkNown";5;"may";50;1;-1;0;"unkNown";"no"
8 43;"technician";"single";"secondary";"no";593;"yes";"no";"unkNown";5;"may";55;1;-1;0;"unkNown";"no"
9 41;"admin.";"divorced";"secondary";"no";270;"yes";"no";"unkNown";5;"may";222;1;-1;0;"unkNown";"no"
解决方法
你可以这样做:
import pandas as pd
df=pd.read_csv("<filename.csv>",sep=";") #Or you may use delimiter=";"
print(df)
您文件的列由 ;
分隔,因此我们将分隔符指定为 ;
。
您可以从 documentation 获得有关 read_csv
的更多信息。
您可以使用 delimiter
函数的 read_csv
参数将分隔字符设置为
df = pd.read_csv(''bank-full.csv'',delimiter='';'')
numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32
我已经把我对read_csv的一些复杂的调用归结为这个简单的测试用例。我实际上在我的“真实”场景中使用转换器的参数,但我删除了为简单。
下面是我的ipython会话:
>>> cat test.out a b 0.76398 0.81394 0.32136 0.91063 >>> import pandas >>> import numpy >>> x = pandas.read_csv('test.out',dtype={'a': numpy.float32},delim_whitespace=True) >>> x a b 0 0.76398 0.81394 1 0.32136 0.91063 >>> x.a.dtype dtype('float64')
我也试过这个用numpy.int32或numpy.int64的dtype。这些选择导致异常:
AttributeError: 'nonetype' object has no attribute 'dtype'
我假设AttributeError是因为pandas不会自动尝试转换/截断浮点值为整数?
我在一个32位的机器上运行32位版本的Python。
>>> !uname -a Linux ubuntu 3.0.0-13-generic #22-Ubuntu SMP Wed Nov 2 13:25:36 UTC 2011 i686 i686 i386 GNU/Linux >>> import platform >>> platform.architecture() ('32bit','ELF') >>> pandas.__version__ '0.10.1'
解决方法
见http://pandas.pydata.org/pandas-docs/dev/whatsnew.html#dtype-specification
你可以在0.11这样做:
# dont' use dtype converters explicity for the columns you care about # they will be converted to float64 if possible,or object if they cannot df = pd.read_csv('test.csv'.....) #### this is optional and related to the issue you posted #### # force anything that is not a numeric to nan # columns are the list of columns that you are interesetd in df[columns] = df[columns].convert_objects(convert_numeric=True) # astype df[columns] = df[columns].astype('float32') see http://pandas.pydata.org/pandas-docs/dev/basics.html#object-conversion Its not as efficient as doing it directly in read_csv (but that requires
我已经确认用0.11-dev,这个DOES工作(对32位和64位,结果是一样的)
In [5]: x = pd.read_csv(StringIO.StringIO(data),dtype={'a': np.float32},delim_whitespace=True) In [6]: x Out[6]: a b 0 0.76398 0.81394 1 0.32136 0.91063 In [7]: x.dtypes Out[7]: a float32 b float64 dtype: object In [8]: pd.__version__ Out[8]: '0.11.0.dev-385ff82' In [9]: quit() vagrant@precise32:~/pandas$ uname -a Linux precise32 3.2.0-23-generic-pae #36-Ubuntu SMP Tue Apr 10 22:19:09 UTC 2012 i686 i686 i386 GNU/Linux some low-level changes)
pandas read_csv dtype前导零
因此,我正在从NOAA读取站代码csv文件,如下所示:
"USAF","WBAN","STATION NAME","CTRY","FIPS","STATE","CALL","LAT","LON","ELEV(.1M)","BEGIN","END""006852","99999","SENT","SW","SZ","","","+46817","+010350","+14200","","""007005","99999","CWOS 07005","","","","","-99999","-999999","-99999","20120127","20120127"
前两列包含气象站代码,有时它们的前导零。当熊猫在未指定dtype的情况下导入它们时,它们将变成整数。没什么大不了的,因为我可以遍历数据帧索引并用类似的东西替换它们,”%06d” % i因为它们始终是六位数字,但是您知道…这是懒惰的方式。
使用以下代码获取csv:
file = urllib.urlopen(r"ftp://ftp.ncdc.noaa.gov/pub/data/inventories/ISH-HISTORY.CSV")output = open(''Station Codes.csv'',''wb'')output.write(file.read())output.close()
一切都很好,但是当我尝试使用此方法阅读时:
import pandas as pddf = pd.io.parsers.read_csv("Station Codes.csv",dtype={''USAF'': np.str, ''WBAN'': np.str})
要么
import pandas as pddf = pd.io.parsers.read_csv("Station Codes.csv",dtype={''USAF'': str, ''WBAN'': str})
我收到一个讨厌的错误消息:
File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 401, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 216, in _read return parser.read() File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 633, in read ret = self._engine.read(nrows) File "C:\Python27\lib\site-packages\pandas-0.11.0-py2.7-win32.egg\pandas\io\parsers.py", line 957, in read data = self._reader.read(nrows) File "parser.pyx", line 654, in pandas._parser.TextReader.read (pandas\src\parser.c:5931) File "parser.pyx", line 676, in pandas._parser.TextReader._read_low_memory (pandas\src\parser.c:6148) File "parser.pyx", line 752, in pandas._parser.TextReader._read_rows (pandas\src\parser.c:6962) File "parser.pyx", line 837, in pandas._parser.TextReader._convert_column_data (pandas\src\parser.c:7898) File "parser.pyx", line 887, in pandas._parser.TextReader._convert_tokens (pandas\src\parser.c:8483) File "parser.pyx", line 953, in pandas._parser.TextReader._convert_with_dtype (pandas\src\parser.c:9535) File "parser.pyx", line 1283, in pandas._parser._to_fw_string (pandas\src\parser.c:14616)TypeError: data type not understood
这是一个相当大的csv(3万1千行),所以也许与此有关吗?
答案1
小编典典这是pandas dtype猜测的问题。
pandas看到数字,然后猜测您希望它是数字。
为了使熊猫不怀疑您的意图,应设置所需的dtype: object
pd.read_csv(''filename.csv'', dtype={''leading_zero_column_name'': object})
会成功的
更新,因为它可以帮助其他人:
要将所有列都设为str,可以执行此操作(根据评论):
pd.read_csv(''sample.csv'', dtype = str)
要将大多数或选择性的列设为str,可以执行以下操作:
# lst of column names which needs to be stringlst_str_cols = [''prefix'', ''serial'']# use dictionary comprehension to make dict of dtypesdict_dtypes = {x : ''str'' for x in lst_str_cols}# use dict on dtypespd.read_csv(''sample.csv'', dtype=dict_dtypes)
Pandas read_csv low_memory 和 dtype 选项
打电话时
df = pd.read_csv('somefile.csv')
我得到:
/Users/josh/anaconda/envs/py27/lib/python2.7/site-
packages/pandas/io/parsers.py:1130:DtypeWarning:列(4、5、7、16)有混合类型。在导入时指定
dtype 选项或设置 low_memory=False。
为什么该dtype
选项与 相关low_memory
,为什么让它False
有助于解决这个问题?
我们今天的关于熊猫read_csv dtype读取所有列,但很少读取为字符串和panda读取csv文件的分享已经告一段落,感谢您的关注,如果您想了解更多关于Kaggle 的 Csv 将所有列放入 1 - 如何与 pd.read_csv 分开并使 df 可用、numpy – 在pandas 0.10.1上使用pandas.read_csv指定dtype float32、pandas read_csv dtype前导零、Pandas read_csv low_memory 和 dtype 选项的相关信息,请在本站查询。
本文标签: