In [12]: df2.dtypesOut[12]: A float64B datetime64[ns]C float32D int32E categoryF objectdtype: object
If you’re using IPython, tab completion for column names (as well as public attributes) is automatically enabled. Here’s a subset of the attributes that will be completed:
As you can see, the columns A, B, C, and D are automatically tab completed. E is there as well; the rest of the attributes have been truncated for brevity.
In [21]: df.sort_index(axis=1,ascending=False)Out[21]: D C B A2013-01-01 -1.135632 -1.509059 -0.282863 0.4691122013-01-02 -1.044236 0.119209 -0.173215 1.2121122013-01-03 1.071804 -0.494929 -2.104569 -0.8618492013-01-04 0.271860 -1.039575 -0.706771 0.7215552013-01-05 -1.087401 0.276232 0.567020 -0.4249722013-01-06 0.524988 -1.478427 0.113648 -0.673690
Sorting by values
In [22]: df.sort(columns='B')Out[22]: A B C D2013-01-03 -0.861849 -2.104569 -0.494929 1.0718042013-01-04 0.721555 -0.706771 -1.039575 0.2718602013-01-01 0.469112 -0.282863 -1.509059 -1.1356322013-01-02 1.212112 -0.173215 0.119209 -1.0442362013-01-06 -0.673690 0.113648 -1.478427 0.5249882013-01-05 -0.424972 0.567020 0.276232 -1.087401
Selection
Note
While standard Python / Numpy expressions for selecting and setting are intuitive and come in handy for interactive work, for production code, we recommend the optimized pandas data access methods, .at, .iat, .loc, .iloc and .ix.
In [32]: df.iloc[3]Out[32]: A 0.721555B -0.706771C -1.039575D 0.271860Name: 2013-01-04 00:00:00, dtype: float64
By integer slices, acting similar to numpy/python
In [33]: df.iloc[3:5,0:2]Out[33]: A B2013-01-04 0.721555 -0.7067712013-01-05 -0.424972 0.567020
By lists of integer position locations, similar to the numpy/python style
In [34]: df.iloc[[1,2,4],[0,2]]Out[34]: A C2013-01-02 1.212112 0.1192092013-01-03 -0.861849 -0.4949292013-01-05 -0.424972 0.276232
For slicing rows explicitly
In [35]: df.iloc[1:3,:]Out[35]: A B C D2013-01-02 1.212112 -0.173215 0.119209 -1.0442362013-01-03 -0.861849 -2.104569 -0.494929 1.071804
For slicing columns explicitly
In [36]: df.iloc[:,1:3]Out[36]: B C2013-01-01 -0.282863 -1.5090592013-01-02 -0.173215 0.1192092013-01-03 -2.104569 -0.4949292013-01-04 -0.706771 -1.0395752013-01-05 0.567020 0.2762322013-01-06 0.113648 -1.478427
For getting a value explicitly
In [37]: df.iloc[1,1]Out[37]: -0.17321464905330861
For getting fast access to a scalar (equiv to the prior method)
In [38]: df.iat[1,1]Out[38]: -0.17321464905330861
Boolean Indexing
Using a single column’s values to select data.
In [39]: df[df.A>0]Out[39]: A B C D2013-01-01 0.469112 -0.282863 -1.509059 -1.1356322013-01-02 1.212112 -0.173215 0.119209 -1.0442362013-01-04 0.721555 -0.706771 -1.039575 0.271860
A where operation for getting.
In [40]: df[df>0]Out[40]: A B C D2013-01-01 0.469112 NaN NaN NaN2013-01-02 1.212112 NaN 0.119209 NaN2013-01-03 NaN NaN NaN 1.0718042013-01-04 0.721555 NaN NaN 0.2718602013-01-05 NaN 0.567020 0.276232 NaN2013-01-06 NaN 0.113648 NaN 0.524988
In [51]: dfOut[51]: A B C D F2013-01-01 0.000000 0.000000 -1.509059 5 NaN2013-01-02 1.212112 -0.173215 0.119209 5 12013-01-03 -0.861849 -2.104569 -0.494929 5 22013-01-04 0.721555 -0.706771 -1.039575 5 32013-01-05 -0.424972 0.567020 0.276232 5 42013-01-06 -0.673690 0.113648 -1.478427 5 5
A where operation with setting.
In [52]: df2=df.copy()In [53]: df2[df2>0]=-df2In [54]: df2Out[54]: A B C D F2013-01-01 0.000000 0.000000 -1.509059 -5 NaN2013-01-02 -1.212112 -0.173215 -0.119209 -5 -12013-01-03 -0.861849 -2.104569 -0.494929 -5 -22013-01-04 -0.721555 -0.706771 -1.039575 -5 -32013-01-05 -0.424972 -0.567020 -0.276232 -5 -42013-01-06 -0.673690 -0.113648 -1.478427 -5 -5
Missing Data
pandas primarily uses the value np.nan to represent missing data. It is by default not included in computations. See the Missing Data section
Reindexing allows you to change/add/delete the index on a specified axis. This returns a copy of the data.
In [55]: df1=df.reindex(index=dates[0:4],columns=list(df.columns)+['E'])In [56]: df1.loc[dates[0]:dates[1],'E']=1In [57]: df1Out[57]: A B C D F E2013-01-01 0.000000 0.000000 -1.509059 5 NaN 12013-01-02 1.212112 -0.173215 0.119209 5 1 12013-01-03 -0.861849 -2.104569 -0.494929 5 2 NaN2013-01-04 0.721555 -0.706771 -1.039575 5 3 NaN
To drop any rows that have missing data.
In [58]: df1.dropna(how='any')Out[58]: A B C D F E2013-01-02 1.212112 -0.173215 0.119209 5 1 1
Filling missing data
In [59]: df1.fillna(value=5)Out[59]: A B C D F E2013-01-01 0.000000 0.000000 -1.509059 5 5 12013-01-02 1.212112 -0.173215 0.119209 5 1 12013-01-03 -0.861849 -2.104569 -0.494929 5 2 52013-01-04 0.721555 -0.706771 -1.039575 5 3 5
To get the boolean mask where values are nan
In [60]: pd.isnull(df1)Out[60]: A B C D F E2013-01-01 False False False False True False2013-01-02 False False False False False False2013-01-03 False False False False False True2013-01-04 False False False False False True
Operating with objects that have different dimensionality and need alignment. In addition, pandas automatically broadcasts along the specified dimension.
In [63]: s=pd.Series([1,3,5,np.nan,6,8],index=dates).shift(2)In [64]: sOut[64]: 2013-01-01 NaN2013-01-02 NaN2013-01-03 12013-01-04 32013-01-05 52013-01-06 NaNFreq: D, dtype: float64In [65]: df.sub(s,axis='index')Out[65]: A B C D F2013-01-01 NaN NaN NaN NaN NaN2013-01-02 NaN NaN NaN NaN NaN2013-01-03 -1.861849 -3.104569 -1.494929 4 12013-01-04 -2.278445 -3.706771 -4.039575 2 02013-01-05 -5.424972 -4.432980 -4.723768 0 -12013-01-06 NaN NaN NaN NaN NaN
Apply
Applying functions to the data
In [66]: df.apply(np.cumsum)Out[66]: A B C D F2013-01-01 0.000000 0.000000 -1.509059 5 NaN2013-01-02 1.212112 -0.173215 -1.389850 10 12013-01-03 0.350263 -2.277784 -1.884779 15 32013-01-04 1.071818 -2.984555 -2.924354 20 62013-01-05 0.646846 -2.417535 -2.648122 25 102013-01-06 -0.026844 -2.303886 -4.126549 30 15In [67]: df.apply(lambdax:x.max()-x.min())Out[67]: A 2.073961B 2.671590C 1.785291D 0.000000F 4.000000dtype: float64
Series is equipped with a set of string processing methods in the str attribute that make it easy to operate on each element of the array, as in the code snippet below. Note that pattern-matching in strgenerally uses regular expressions by default (and in some cases always uses them). See more atVectorized String Methods.
pandas provides various facilities for easily combining together Series, DataFrame, and Panel objects with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations.
In [86]: df=pd.DataFrame({'A':['foo','bar','foo','bar', ....:'foo','bar','foo','foo'], ....:'B':['one','one','two','three', ....:'two','two','one','three'], ....:'C':np.random.randn(8), ....:'D':np.random.randn(8)}) ....:In [87]: dfOut[87]: A B C D0 foo one -1.202872 -0.0552241 bar one -1.814470 2.3959852 foo two 1.018601 1.5528253 bar three -0.595447 0.1665994 foo two 1.395433 0.0476095 bar two -0.392670 -0.1364736 foo one 0.007207 -0.5617577 foo three 1.928123 -1.623033
Grouping and then applying a function sum to the resulting groups.
In [88]: df.groupby('A').sum()Out[88]: C DA bar -2.802588 2.42611foo 3.146492 -0.63958
Grouping by multiple columns forms a hierarchical index, which we then apply the function.
In [89]: df.groupby(['A','B']).sum()Out[89]: C DA B bar one -1.814470 2.395985 three -0.595447 0.166599 two -0.392670 -0.136473foo one -1.195665 -0.616981 three 1.928123 -1.623033 two 2.414034 1.600434
In [90]: tuples=list(zip(*[['bar','bar','baz','baz', ....:'foo','foo','qux','qux'], ....:['one','two','one','two', ....:'one','two','one','two']])) ....:In [91]: index=pd.MultiIndex.from_tuples(tuples,names=['first','second'])In [92]: df=pd.DataFrame(np.random.randn(8,2),index=index,columns=['A','B'])In [93]: df2=df[:4]In [94]: df2Out[94]: A Bfirst second bar one 0.029399 -0.542108 two 0.282696 -0.087302baz one -1.575170 1.771208 two 0.816482 1.100230
The stack function “compresses” a level in the DataFrame’s columns.
In [95]: stacked=df2.stack()In [96]: stackedOut[96]: first second bar one A 0.029399 B -0.542108 two A 0.282696 B -0.087302baz one A -1.575170 B 1.771208 two A 0.816482 B 1.100230dtype: float64
With a “stacked” DataFrame or Series (having a MultiIndex as the index), the inverse operation of stackis unstack, which by default unstacks the last level:
In [97]: stacked.unstack()Out[97]: A Bfirst second bar one 0.029399 -0.542108 two 0.282696 -0.087302baz one -1.575170 1.771208 two 0.816482 1.100230In [98]: stacked.unstack(1)Out[98]: second one twofirst bar A 0.029399 0.282696 B -0.542108 -0.087302baz A -1.575170 0.816482 B 1.771208 1.100230In [99]: stacked.unstack(0)Out[99]: first bar bazsecond one A 0.029399 -1.575170 B -0.542108 1.771208two A 0.282696 0.816482 B -0.087302 1.100230
In [100]: df=pd.DataFrame({'A':['one','one','two','three']*3, .....:'B':['A','B','C']*4, .....:'C':['foo','foo','foo','bar','bar','bar']*2, .....:'D':np.random.randn(12), .....:'E':np.random.randn(12)}) .....:In [101]: dfOut[101]: A B C D E0 one A foo 1.418757 -0.1796661 one B foo -1.879024 1.2918362 two C foo 0.536826 -0.0096143 three A bar 1.006160 0.3921494 one B bar -0.029716 0.2645995 one C bar -1.146178 -0.0574096 two A foo 0.100900 -1.4256387 three B foo -1.035018 1.0240988 one C foo 0.314665 -0.1060629 one A bar -0.773723 1.82437510 two B bar -1.170653 0.59597411 three C bar 0.648740 1.167115
We can produce pivot tables from this data very easily:
In [102]: pd.pivot_table(df,values='D',index=['A','B'],columns=['C'])Out[102]: C bar fooA B one A -0.773723 1.418757 B -0.029716 -1.879024 C -1.146178 0.314665three A 1.006160 NaN B NaN -1.035018 C 0.648740 NaNtwo A NaN 0.100900 B -1.170653 NaN C NaN 0.536826
Time Series
pandas has simple, powerful, and efficient functionality for performing resampling operations during frequency conversion (e.g., converting secondly data into 5-minutely data). This is extremely common in, but not limited to, financial applications. See the Time Series section
Converting between period and timestamp enables some convenient arithmetic functions to be used. In the following example, we convert a quarterly frequency with year ending in November to 9am of the end of the month following the quarter end:
Rename the categories to more meaningful names (assigning to Series.cat.categories is inplace!)
In [125]: df["grade"].cat.categories=["very good","good","very bad"]
Reorder the categories and simultaneously add the missing categories (methods under Series.catreturn a new Series per default).
In [126]: df["grade"]=df["grade"].cat.set_categories(["very bad","bad","medium","good","very good"])In [127]: df["grade"]Out[127]: 0 very good1 good2 good3 very good4 very good5 very badName: grade, dtype: categoryCategories (5, object): [very bad < bad < medium < good < very good]
Sorting is per order in the categories, not lexical order.
In [128]: df.sort("grade")Out[128]: id raw_grade grade5 6 e very bad1 2 b good2 3 b good0 1 a very good3 4 a very good4 5 a very good
Grouping by a categorical column shows also empty categories.
In [129]: df.groupby("grade").size()Out[129]: gradevery bad 1bad NaNmedium NaNgood 2very good 3dtype: float64
If you are trying an operation and you see an exception like:
>>> ifpd.Series([False,True,False]): print("I was true")Traceback ...ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
See Comparisons for an explanation and what to do.