下载课件后,根据视频练习。
>>> df = pd.read_csv("/Users/chentianwei/自我练习/python练习/NBAPlayers.txt", sep=' ') . # 符号是制表符,安装 来分割,即遇到 就跳到下一个制表符。
d.head(n)
>>> df.head(); Player height weight ... born birth_city birth_state 0 Curly Armstrong 180.0 77.0 ... 1918.0 NaN NaN 1 Cliff Barker 188.0 83.0 ... 1921.0 Yorktown Indiana 2 Leo Barnhorst 193.0 86.0 ... 1924.0 NaN NaN 3 Ed Bartels 196.0 88.0 ... 1925.0 NaN NaN 4 Ralph Beard 178.0 79.0 ... 1927.0 Hardinsburg Kentucky
- head()默认显示前5行,n参数用于指定显示的行的数量。
- tail(n)则是显示后n行
两种数据类型
- series
- DataFrame
Series
class pandas.
Series
(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
- data可以是dict, list, array-like, Iterable, scalar value(比如整数)
- index长度必须等于data的长度。
>>> b = [1,2,3,4,5] >>> s1 = pd.Series(b) >>> s1 0 1 1 2 2 3 3 4 4 5 dtype: int64 >>> s2 = pd.Series(b, index=list('abcde')) >>> s2 a 1 b 2 c 3 d 4 e 5 dtype: int64 >>> s2.index Index(['a', 'b', 'c', 'd', 'e'], dtype='object') >>> s2.values array([1, 2, 3, 4, 5])
- .index方法, 其实就是调用_index
⚠️:Series有非常多的属性和方法
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html?highlight=series
DataFrame
DateFrame.to_numpy()可以把单一类型的对象转化为array类型。⚠️如果是多类型的,成本很高。index,column会被去掉。
创建
可用数据
- Dict of 1D ndarrays, lists, dicts, Series
- 2-D numpy.ndarray
- Structured or record ndarray
- A Series
- Another DataFrame
例子:
a的key转化为列名:
>>> a = dict(name = ["xiaoming", "tom", "Jony"], age = [12,11,32]) >>> pd.DataFrame(data=a, index=list('abc')) name age a xiaoming 12 b tom 11 c Jony 32
例子2:
使用Series,把dict变为series类型。因此DataFrame要,指定列名columns,这是因为转化为series, 原来的key变成了index.。
>>> a {'name': 'Tom', 'age': 18, 'sex': 'male'} >>> s1= pd.Series(a) >>> s1 name Tom age 18 sex male dtype: object >>> pd.DataFrame(s1, columns=["Value"]) Value name Tom age 18 sex male
DataFrame常用的方法和属性
https://pandas.pydata.org/pandas-docs/stable/reference/frame.html
还是使用上面的数据。
属性
>>> df.values array([['Curly Armstrong', 180.0, 77.0, ..., 1918.0, nan, nan], ['Cliff Barker', 188.0, 83.0, ..., 1921.0, 'Yorktown', 'Indiana'], ['Leo Barnhorst', 193.0, 86.0, ..., 1924.0, nan, nan], ..., ['Stephen Zimmerman', 213.0, 108.0, ..., 1996.0, 'Hendersonville', 'Tennessee'], ['Paul Zipser', 203.0, 97.0, ..., 1994.0, 'Heidelberg', 'Germany'], ['Ivica Zubac', 216.0, 120.0, ..., 1997.0, 'Mostar', 'Bosnia and Herzegovina']], dtype=object)
- values,返回一个array,保存了所有行的数据。
>>> df.__dict__.keys() dict_keys(['_is_copy', '_data', '_item_cache']) >>> df._data BlockManager Items: Index(['Player', 'height', 'weight', 'collage', 'born', 'birth_city', 'birth_state'], dtype='object') Axis 1: RangeIndex(start=0, stop=3922, step=1) FloatBlock: [1, 2, 4], 3 x 3922, dtype: float64 ObjectBlock: [0, 3, 5, 6], 4 x 3922, dtype: object
- df的很多属性都可以通过_data看到。
>>> df.index RangeIndex(start=0, stop=3922, step=1) >>> df.columns Index(['Player', 'height', 'weight', 'collage', 'born', 'birth_city', 'birth_state'], dtype='object')
- index返回每行的标签/索引
- column返回的是DataFrame的列标签。
>>> df.dtypes
Player object
height float64
weight float64
collage object
born float64
birth_city object
birth_state object
dtype: object
- dtypes, 返回DataFrame的列中的数据的类型。
>>> df.size 27454 # 即列数*行数,返回的是所有数据的总数量。其实都可以通过_data看出。
>>> df.shape
(3922, 7)
方法:
- head, tail
- rename(index=None, columns=None, axis=None)
- replace (关于字典的用法,过于复杂了,以后再说)
- unique_values (文档没有这个方法。)
- sort_values, 根据值排序,就是sql语法中的order by xxx ascend
- describe
- max/min/sum/mean
- ...
pandas.DataFrame.rename
ataFrame.
rename
(self, mapper=None, index=None, columns=None, axis=None, copy=True)
- mapper是一个字典类型的对象或者一个函数,和axis参数配合使用。
- axis : int or str. Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’.
- index: 字典类对象或函数。(mapper, axis=0)相当于index=mapper。
- columns: (mapper, axis= 1) 相当于 columns = mapper
- ⚠️copy默认是True, 即是copy underlying data。
⚠️需要主要的是df.rename()是建立一个新的副本,因此要重新分配指针。 df = df.rename()
DataFrame.
sort_values
(self, by, axis=0, ascending=True)
>>> df = pd.DataFrame({ ... 'col1': ['A', 'A', 'B', np.nan, 'D', 'C'], ... 'col2': [2, 1, 9, 8, 7, 4], ... 'col3': [0, 1, 9, 4, 2, 3],}) >>> df col1 col2 col3 0 A 2 0 1 A 1 1 2 B 9 9 3 NaN 8 4 4 D 7 2 5 C 4 3 >>> df.sort_values(by=['col1']) col1 col2 col3 0 A 2 0 1 A 1 1 2 B 9 9 5 C 4 3 4 D 7 2 3 NaN 8 4
max(), describe()方法的使用
- max(axis=None) ⚠️axis: {index:(0), columns:(1)}
>>> df.max() col2 9 col3 9 dtype: int64 >>> df.describe() col2 col3 count 6.000000 6.000000 mean 5.166667 3.166667 std 3.311596 3.188521 min 1.000000 0.000000 25% 2.500000 1.250000 50% 5.500000 2.500000 75% 7.750000 3.750000 max 9.000000 9.000000