通常对数据的矩阵进行操作,就用numpy操作,打开txt文件
使用help()去查询文档,可以看到官方的注释
  1. import numpy
  2. path = r'F:\数据分析专用\数据分析与机器学习\world_alcohol.txt'
  3. world_alchol = numpy.genfromtxt(path, delimiter=",", dtype=str)
  4. print(type(world_alchol))
  5. print(world_alchol)
  6. print(help(numpy.genfromtxt))
  1. <class 'numpy.ndarray'>
  2. [['Year' 'WHO region' 'Country' 'Beverage Types' 'Display Value']
  3. ['' 'Western Pacific' 'Viet Nam' 'Wine' '']
  4. ['' 'Americas' 'Uruguay' 'Other' '0.5']
  5. ...
  6. ['' 'Africa' 'Malawi' 'Other' '0.75']
  7. ['' 'Americas' 'Bahamas' 'Wine' '1.5']
  8. ['' 'Africa' 'Malawi' 'Spirits' '0.31']]
  9. Help on function genfromtxt in module numpy.lib.npyio:
  10.  
  11. genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None, encoding='bytes')
  12. Load data from a text file, with missing values handled as specified.
  13.  
  14. Each line past the first `skip_header` lines is split at the `delimiter`
  15. character, and characters following the `comments` character are discarded.
  16.  
  17. Parameters
  18. ----------
  19. fname : file, str, pathlib.Path, list of str, generator
  20. File, filename, list, or generator to read. If the filename
  21. extension is `.gz` or `.bz2`, the file is first decompressed. Note
  22. that generators must return byte strings in Python 3k. The strings
  23. in a list or produced by a generator are treated as lines.
  24. dtype : dtype, optional
  25. Data type of the resulting array.
  26. If None, the dtypes will be determined by the contents of each
  27. column, individually.
  28. comments : str, optional
  29. The character used to indicate the start of a comment.
  30. All the characters occurring on a line after a comment are discarded
  31. delimiter : str, int, or sequence, optional
  32. The string used to separate values. By default, any consecutive
  33. whitespaces act as delimiter. An integer or sequence of integers
  34. can also be provided as width(s) of each field.
  35. skiprows : int, optional
  36. `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
  37. skip_header : int, optional
  38. The number of lines to skip at the beginning of the file.
  39. skip_footer : int, optional
  40. The number of lines to skip at the end of the file.
  41. converters : variable, optional
  42. The set of functions that convert the data of a column to a value.
  43. The converters can also be used to provide a default value
  44. for missing data: ``converters = {3: lambda s: float(s or 0)}``.
  45. missing : variable, optional
  46. `missing` was removed in numpy 1.10. Please use `missing_values`
  47. instead.
  48. missing_values : variable, optional
  49. The set of strings corresponding to missing data.
  50. filling_values : variable, optional
  51. The set of values to be used as default when the data are missing.
  52. usecols : sequence, optional
  53. Which columns to read, with 0 being the first. For example,
  54. ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
  55. names : {None, True, str, sequence}, optional
  56. If `names` is True, the field names are read from the first line after
  57. the first `skip_header` lines. This line can optionally be proceeded
  58. by a comment delimeter. If `names` is a sequence or a single-string of
  59. comma-separated names, the names will be used to define the field names
  60. in a structured dtype. If `names` is None, the names of the dtype
  61. fields will be used, if any.
  62. excludelist : sequence, optional
  63. A list of names to exclude. This list is appended to the default list
  64. ['return','file','print']. Excluded names are appended an underscore:
  65. for example, `file` would become `file_`.
  66. deletechars : str, optional
  67. A string combining invalid characters that must be deleted from the
  68. names.
  69. defaultfmt : str, optional
  70. A format used to define default field names, such as "f%i" or "f_%02i".
  71. autostrip : bool, optional
  72. Whether to automatically strip white spaces from the variables.
  73. replace_space : char, optional
  74. Character(s) used in replacement of white spaces in the variables
  75. names. By default, use a '_'.
  76. case_sensitive : {True, False, 'upper', 'lower'}, optional
  77. If True, field names are case sensitive.
  78. If False or 'upper', field names are converted to upper case.
  79. If 'lower', field names are converted to lower case.
  80. unpack : bool, optional
  81. If True, the returned array is transposed, so that arguments may be
  82. unpacked using ``x, y, z = loadtxt(...)``
  83. usemask : bool, optional
  84. If True, return a masked array.
  85. If False, return a regular array.
  86. loose : bool, optional
  87. If True, do not raise errors for invalid values.
  88. invalid_raise : bool, optional
  89. If True, an exception is raised if an inconsistency is detected in the
  90. number of columns.
  91. If False, a warning is emitted and the offending lines are skipped.
  92. max_rows : int, optional
  93. The maximum number of rows to read. Must not be used with skip_footer
  94. at the same time. If given, the value must be at least 1. Default is
  95. to read the entire file.
  96.  
  97. .. versionadded:: 1.10.0
  98. encoding : str, optional
  99. Encoding used to decode the inputfile. Does not apply when `fname` is
  100. a file object. The special value 'bytes' enables backward compatibility
  101. workarounds that ensure that you receive byte arrays when possible
  102. and passes latin1 encoded strings to converters. Override this value to
  103. receive unicode arrays and pass strings as input to converters. If set
  104. to None the system default is used. The default value is 'bytes'.
  105.  
  106. .. versionadded:: 1.14.0
  107.  
  108. Returns
  109. -------
  110. out : ndarray
  111. Data read from the text file. If `usemask` is True, this is a
  112. masked array.
  113.  
  114. See Also
  115. --------
  116. numpy.loadtxt : equivalent function when no data is missing.
  117.  
  118. Notes
  119. -----
  120. * When spaces are used as delimiters, or when no delimiter has been given
  121. as input, there should not be any missing data between two fields.
  122. * When the variables are named (either by a flexible dtype or with `names`,
  123. there must not be any header in the file (else a ValueError
  124. exception is raised).
  125. * Individual values are not stripped of spaces by default.
  126. When using a custom converter, make sure the function does remove spaces.
  127.  
  128. References
  129. ----------
  130. .. [1] NumPy User Guide, section `I/O with NumPy
  131. <http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.
  132.  
  133. Examples
  134. ---------
  135. >>> from io import StringIO
  136. >>> import numpy as np
  137.  
  138. Comma delimited file with mixed dtype
  139.  
  140. >>> s = StringIO("1,1.3,abcde")
  141. >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
  142. ... ('mystring','S5')], delimiter=",")
  143. >>> data
  144. array((1, 1.3, 'abcde'),
  145. dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
  146.  
  147. Using dtype = None
  148.  
  149. >>> s.seek(0) # needed for StringIO example only
  150. >>> data = np.genfromtxt(s, dtype=None,
  151. ... names = ['myint','myfloat','mystring'], delimiter=",")
  152. >>> data
  153. array((1, 1.3, 'abcde'),
  154. dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
  155.  
  156. Specifying dtype and names
  157.  
  158. >>> s.seek(0)
  159. >>> data = np.genfromtxt(s, dtype="i8,f8,S5",
  160. ... names=['myint','myfloat','mystring'], delimiter=",")
  161. >>> data
  162. array((1, 1.3, 'abcde'),
  163. dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
  164.  
  165. An example with fixed-width columns
  166.  
  167. >>> s = StringIO("11.3abcde")
  168. >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
  169. ... delimiter=[1,3,5])
  170. >>> data
  171. array((1, 1.3, 'abcde'),
  172. dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])
  173.  
  174. None

用array输入数组

  1. vector = numpy.array([5, 10, 15, 20])
  2. matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
  3. print(vector)
  4. print(matrix)

输出结果

[ 5 10 15 20]
[[ 5 10 15]
[20 25 30]
[35 40 45]]
 
numpy.shape是用来判断类型的,返回的值是元祖类型的多维数组的个数
  1. vector = numpy.array([1, 2, 3, 4])
  2. print(vector.shape)
  3. matrix = numpy.array([[5, 10, 15], [20, 25, 30]])
  4. print(matrix.shape)
(4,)
(2, 3)
python中随便往list里存任何数值,都是在numpy里必须存储的是固定的格式,array是不支持任何格式的转换的
以下数据由于有5.0的数值存在,为了满足这个数值,所有的数值都被转换为浮点数了
  1. import numpy
  2. numbers = numpy.array([1, 2, 3, 4, 0, 5.0])
  3. print(numbers)
  4. numbers.dtype

  1. world_alchol = numpy.genfromtxt(path, delimiter=',', dtype=str, skip_header=1)
  2. print(world_alchol)

文件读取

输出的是一个列表,那么读取的时候就可以根据切片读取出列表的值

  1. uruguay_other_1986 = world_alchol[1, 4]
  2. third_country = world_alchol[2, 2]
  3. print(uruguay_other_1986)
  4. print(third_country)

切片取值

【数据分析学习】016-numpy数据结构的更多相关文章

  1. Python数据分析学习之Numpy

    Numpy的简单操作 import numpy #导入numpy包 file = numpy.genfromtxt("文件路径",delimiter=" ",d ...

  2. Python数据分析学习目录

    python数据分析学习目录 Anaconda的安装和更新 矩阵NumPy pandas数据表 matplotlib-2D绘图库学习目录                      

  3. 个人永久性免费-Excel催化剂功能第100波-透视多行数据为多列数据结构

    在数据处理过程中,大量的非预期格式结构需要作转换,有大家熟知的多维转一维(准确来说应该是交叉表结构的数据转二维表标准数据表结构),也同样有一些需要透视操作的数据源,此篇同样提供更便捷的方法实现此类数据 ...

  4. Python数据分析学习(二):Numpy数组对象基础

    1.1数组对象基础 .caret, .dropup > .btn > .caret { border-top-color: #000 !important; } .label { bord ...

  5. Python数据分析学习(一):Numpy与纯Python计算向量加法速度比较

    import sys from datetime import datetime import numpy as np def numpysum(n): a = np.arange(n) ** 2 b ...

  6. python数据分析学习(2)pandas二维工具DataFrame讲解

    目录 二:pandas数据结构介绍   下面继续讲解pandas的第二个工具DataFrame. 二:pandas数据结构介绍 2.DataFarme   DataFarme表示的是矩阵的数据表,包含 ...

  7. python数据分析学习(1)pandas一维工具Series讲解

    目录 一:pandas数据结构介绍   python是数据分析的主要工具,它包含的数据结构和数据处理工具的设计让python在数据分析领域变得十分快捷.它以NumPy为基础,并对于需要类似 for循环 ...

  8. 数据分析学习(zhuan)

    http://www.zhihu.com/question/22119753 http://www.zhihu.com/question/20757000 ********************** ...

  9. [python]-数据科学库Numpy学习

    一.Numpy简介: Python中用列表(list)保存一组值,可以用来当作数组使用,不过由于列表的元素可以是任何对象,因此列表中所保存的是对象的指针.这样为了保存一个简单的[1,2,3],需要有3 ...

随机推荐

  1. tp5 权限设置

    ============================== <?php/** * Created by PhpStorm. * User: 14155 * Date: 2018/11/10 * ...

  2. RONOJ——PID204 / 特种部队 ☆

    题目描述 某特种部队接到一个任务,需要潜入一个仓库.该部队士兵分为两路,第一路士兵已经在正面 牵制住了敌人,第二路士兵正在悄悄地从后方秘密潜入敌人的仓库. 当他们到达仓库时候,发现这个仓库的锁是一把很 ...

  3. atomikos实现多数据源支持分布式事务管理(spring、tomcat、JTA)

    原文链接:http://iteye.blog.163.com/blog/static/1863080962012102945116222/   Atomikos TransactionsEssenti ...

  4. HDU 5402 Travelling Salesman Problem (模拟 有规律)(左上角到右下角路径权值最大,输出路径)

    Travelling Salesman Problem Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 65536/65536 K (J ...

  5. Android 5.0 怎样正确启用isLoggable(二)__原理分析

    前置文章 <Android 5.0 怎样正确启用isLoggable(一)__使用具体解释> 概要 在上文<Android 5.0 怎样正确启用isLoggable(一)__使用具体 ...

  6. 关于使用chrome插件改动全部的站点的响应responseHeaders头的注意

    1 眼下我掌握的调试技巧非常不方便,如今使用的是浏览器动作,每次都须要点击那个popup页面弹出,然后右键->查看元素,才干显示它的调试面板.一点击某些位置它又没有了; 2 改动响应报头的值时, ...

  7. Composer 很重要很重要 内核 原理

    话题先攒着,过来再来写 先来一张原理图 composer的原理和其他的包管理工具都是一样的,只是实现的细节有些不同,例如yum,例如brew,例如apt-get还有packets. 使用自己的comp ...

  8. Java缓存server调优

    搜索降级方案中xmn開始使用bizer默认的128M,很慢. 偶然改成1G,效果立刻上来,可是xmx调大并没有明显效果.                  100并发             200并 ...

  9. MySQL调优 —— Using temporary

      DBA发来一个线上慢查询问题. SQL例如以下(为突出重点省略部分内容): select distinct article0_.id, 等字段 from article_table article ...

  10. 深入Session

    早上考虑Spring MVC和Structs2项目共用时看到一个问题,如何保持session一致?Session是怎么样被服务器处理的呢,Spring MVC中是如何封装处理Session并在不同请求 ...