Pandas之:深入理解Pandas的数据结构
文章目錄
- 簡介
- Series
- 從**ndarray**創(chuàng)建
- 從dict創(chuàng)建
- 從標(biāo)量創(chuàng)建
- Series 和 ndarray
- Series和dict
- 矢量化操作和標(biāo)簽對齊
- Name屬性
- **DataFrame**
- 從Series創(chuàng)建
- 從ndarrays 和 lists創(chuàng)建
- 從結(jié)構(gòu)化數(shù)組創(chuàng)建
- 從字典list創(chuàng)建
- 從元組中創(chuàng)建
- 列選擇,添加和刪除
簡介
本文將會講解Pandas中基本的數(shù)據(jù)類型Series和DataFrame,并詳細(xì)講解這兩種類型的創(chuàng)建,索引等基本行為。
使用Pandas需要引用下面的lib:
In [1]: import numpy as npIn [2]: import pandas as pdSeries
Series是一維帶label和index的數(shù)組。我們使用下面的方法來創(chuàng)建一個Series:
>>> s = pd.Series(data, index=index)這里的data可以是Python的字典,np的ndarray,或者一個標(biāo)量。
index是一個橫軸label的list。接下來我們分別來看下怎么創(chuàng)建Series。
從ndarray創(chuàng)建
s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])s Out[67]: a -1.300797 b -2.044172 c -1.170739 d -0.445290 e 1.208784 dtype: float64使用index獲取index:
s.index Out[68]: Index(['a', 'b', 'c', 'd', 'e'], dtype='object')從dict創(chuàng)建
d = {'b': 1, 'a': 0, 'c': 2}pd.Series(d) Out[70]: a 0 b 1 c 2 dtype: int64從標(biāo)量創(chuàng)建
pd.Series(5., index=['a', 'b', 'c', 'd', 'e']) Out[71]: a 5.0 b 5.0 c 5.0 d 5.0 e 5.0 dtype: float64Series 和 ndarray
Series和ndarray是很類似的,在Series中使用index數(shù)值表現(xiàn)的就像ndarray:
s[0] Out[72]: -1.3007972194268396s[:3] Out[73]: a -1.300797 b -2.044172 c -1.170739 dtype: float64s[s > s.median()] Out[74]: d -0.445290 e 1.208784 dtype: float64s[[4, 3, 1]] Out[75]: e 1.208784 d -0.445290 b -2.044172 dtype: float64Series和dict
如果使用label來訪問Series,那么它的表現(xiàn)就和dict很像:
s['a'] Out[80]: -1.3007972194268396s['e'] = 12.s Out[82]: a -1.300797 b -2.044172 c -1.170739 d -0.445290 e 12.000000 dtype: float64矢量化操作和標(biāo)簽對齊
Series可以使用更加簡單的矢量化操作:
s + s Out[83]: a -2.601594 b -4.088344 c -2.341477 d -0.890581 e 24.000000 dtype: float64s * 2 Out[84]: a -2.601594 b -4.088344 c -2.341477 d -0.890581 e 24.000000 dtype: float64np.exp(s) Out[85]: a 0.272315 b 0.129487 c 0.310138 d 0.640638 e 162754.791419 dtype: float64Name屬性
Series還有一個name屬性,我們可以在創(chuàng)建的時候進(jìn)行設(shè)置:
s = pd.Series(np.random.randn(5), name='something')s Out[88]: 0 0.192272 1 0.110410 2 1.442358 3 -0.375792 4 1.228111 Name: something, dtype: float64s還有一個rename方法,可以重命名s:
s2 = s.rename("different")DataFrame
DataFrame是一個二維的帶label的數(shù)據(jù)結(jié)構(gòu),它是由Series組成的,你可以把DataFrame看成是一個excel表格。DataFrame可以由下面幾種數(shù)據(jù)來創(chuàng)建:
- 一維的ndarrays, lists, dicts, 或者 Series
- 結(jié)構(gòu)化數(shù)組創(chuàng)建
- 2維的numpy.ndarray
- 其他的DataFrame
從Series創(chuàng)建
可以從Series構(gòu)成的字典中來創(chuàng)建DataFrame:
d = {'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']),'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}df = pd.DataFrame(d)df Out[92]: one two a 1.0 1.0 b 2.0 2.0 c 3.0 3.0 d NaN 4.0進(jìn)行index重排:
pd.DataFrame(d, index=['d', 'b', 'a']) Out[93]: one two d NaN 4.0 b 2.0 2.0 a 1.0 1.0進(jìn)行列重排:
pd.DataFrame(d, index=['d', 'b', 'a'], columns=['two', 'three']) Out[94]: two three d 4.0 NaN b 2.0 NaN a 1.0 NaN從ndarrays 和 lists創(chuàng)建
d = {'one': [1., 2., 3., 4.],'two': [4., 3., 2., 1.]}pd.DataFrame(d) Out[96]: one two 0 1.0 4.0 1 2.0 3.0 2 3.0 2.0 3 4.0 1.0pd.DataFrame(d, index=['a', 'b', 'c', 'd']) Out[97]: one two a 1.0 4.0 b 2.0 3.0 c 3.0 2.0 d 4.0 1.0從結(jié)構(gòu)化數(shù)組創(chuàng)建
可以從結(jié)構(gòu)化數(shù)組中創(chuàng)建DF:
In [47]: data = np.zeros((2, ), dtype=[('A', 'i4'), ('B', 'f4'), ('C', 'a10')])In [48]: data[:] = [(1, 2., 'Hello'), (2, 3., "World")]In [49]: pd.DataFrame(data) Out[49]: A B C 0 1 2.0 b'Hello' 1 2 3.0 b'World'In [50]: pd.DataFrame(data, index=['first', 'second']) Out[50]: A B C first 1 2.0 b'Hello' second 2 3.0 b'World'In [51]: pd.DataFrame(data, columns=['C', 'A', 'B']) Out[51]: C A B 0 b'Hello' 1 2.0 1 b'World' 2 3.0從字典list創(chuàng)建
In [52]: data2 = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]In [53]: pd.DataFrame(data2) Out[53]: a b c 0 1 2 NaN 1 5 10 20.0In [54]: pd.DataFrame(data2, index=['first', 'second']) Out[54]: a b c first 1 2 NaN second 5 10 20.0In [55]: pd.DataFrame(data2, columns=['a', 'b']) Out[55]: a b 0 1 2 1 5 10從元組中創(chuàng)建
可以從元組中創(chuàng)建更加復(fù)雜的DF:
In [56]: pd.DataFrame({('a', 'b'): {('A', 'B'): 1, ('A', 'C'): 2},....: ('a', 'a'): {('A', 'C'): 3, ('A', 'B'): 4},....: ('a', 'c'): {('A', 'B'): 5, ('A', 'C'): 6},....: ('b', 'a'): {('A', 'C'): 7, ('A', 'B'): 8},....: ('b', 'b'): {('A', 'D'): 9, ('A', 'B'): 10}})....: Out[56]: a b b a c a b A B 1.0 4.0 5.0 8.0 10.0C 2.0 3.0 6.0 7.0 NaND NaN NaN NaN NaN 9.0列選擇,添加和刪除
可以像操作Series一樣操作DF:
In [64]: df['one'] Out[64]: a 1.0 b 2.0 c 3.0 d NaN Name: one, dtype: float64In [65]: df['three'] = df['one'] * df['two']In [66]: df['flag'] = df['one'] > 2In [67]: df Out[67]: one two three flag a 1.0 1.0 1.0 False b 2.0 2.0 4.0 False c 3.0 3.0 9.0 True d NaN 4.0 NaN False可以刪除特定的列,或者pop操作:
In [68]: del df['two']In [69]: three = df.pop('three')In [70]: df Out[70]: one flag a 1.0 False b 2.0 False c 3.0 True d NaN False如果插入常量,那么會填滿整個列:
In [71]: df['foo'] = 'bar'In [72]: df Out[72]: one flag foo a 1.0 False bar b 2.0 False bar c 3.0 True bar d NaN False bar默認(rèn)會插入到DF中最后一列,可以使用insert來指定插入到特定的列:
In [75]: df.insert(1, 'bar', df['one'])In [76]: df Out[76]: one bar flag foo one_trunc a 1.0 1.0 False bar 1.0 b 2.0 2.0 False bar 2.0 c 3.0 3.0 True bar NaN d NaN NaN False bar NaN使用assign 可以從現(xiàn)有的列中衍生出新的列:
In [77]: iris = pd.read_csv('data/iris.data')In [78]: iris.head() Out[78]: SepalLength SepalWidth PetalLength PetalWidth Name 0 5.1 3.5 1.4 0.2 Iris-setosa 1 4.9 3.0 1.4 0.2 Iris-setosa 2 4.7 3.2 1.3 0.2 Iris-setosa 3 4.6 3.1 1.5 0.2 Iris-setosa 4 5.0 3.6 1.4 0.2 Iris-setosaIn [79]: (iris.assign(sepal_ratio=iris['SepalWidth'] / iris['SepalLength'])....: .head())....: Out[79]: SepalLength SepalWidth PetalLength PetalWidth Name sepal_ratio 0 5.1 3.5 1.4 0.2 Iris-setosa 0.686275 1 4.9 3.0 1.4 0.2 Iris-setosa 0.612245 2 4.7 3.2 1.3 0.2 Iris-setosa 0.680851 3 4.6 3.1 1.5 0.2 Iris-setosa 0.673913 4 5.0 3.6 1.4 0.2 Iris-setosa 0.720000注意, assign 會創(chuàng)建一個新的DF,原DF保持不變。
下面用一張表來表示DF中的index和選擇:
| 選擇列 | df[col] | Series |
| 通過label選擇行 | df.loc[label] | Series |
| 通過數(shù)組選擇行 | df.iloc[loc] | Series |
| 行的切片 | df[5:10] | DataFrame |
| 使用boolean向量選擇行 | df[bool_vec] | DataFrame |
本文已收錄于 http://www.flydean.com/03-python-pandas-data-structures/
最通俗的解讀,最深刻的干貨,最簡潔的教程,眾多你不知道的小技巧等你來發(fā)現(xiàn)!
歡迎關(guān)注我的公眾號:「程序那些事」,懂技術(shù),更懂你!
總結(jié)
以上是生活随笔為你收集整理的Pandas之:深入理解Pandas的数据结构的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Pandas之:Pandas简洁教程
- 下一篇: 密码学系列之:feistel ciphe