The columns of the resulting DataFrame have different
dtypes:
In [11]: df2.dtypesOut[11]: A float64B datetime64[s]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 and F are there as well; the rest of the attributes have been
truncated for brevity.
In [32]: df.iloc[3]Out[32]: A 0.721555B -0.706771C -1.039575D 0.271860Name: 2013-01-04 00:00:00, dtype: float64
Boolean indexing
Select rows where df.A is greater than 0.
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
Selecting values from a where a boolean condition is met:
Setting
Setting a new column automatically aligns the data by the indexes:
In [45]: s1=pd.Series([1,2,3,4,5,6],index=pd.date_range("20130102",periods=6))In [46]:
Missing data
For NumPy data types, np.nan represents 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.0 NaN 1.02013-01-02 1.212112 -0.173215 0.119209 5.0 1.0 1.02013-01-03 -0.861849 -2.104569 -0.494929 5.0 2.0 NaN2013-01-04 0.721555 -0.706771 -1.039575 5.0 3.0 NaN
Operating with another Series or DataFrame with a different index or column
will align the result with the union of the index or column labels. In addition, pandas
automatically broadcasts along the specified dimension and will fill unaligned labels with np.nan.
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 1.0
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. See more at Vectorized String Methods.
In [71]: s=pd.Series(["A","B","C","Aaba","Baca",np
Merge
Concat
pandas provides various facilities for easily combining together Series and
DataFrame objects with various kinds of set logic for the indexes
and relational algebra functionality in the case of join / merge-type
operations.
In [87]: 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 [88]: dfOut[88]: A B C D0 foo one 1.346061 -1.5775851 bar one 1.511763 0.3968232 foo two 1.627081 -0.1053813 bar three -0.990582 -0.5325324 foo two -0.441652 1.4537495 bar two 1.211526 1.2088436 foo one 0.268520 -0.0809527 foo three 0.024580 -0.264610
Grouping by a column label, selecting column labels, and then applying the
DataFrameGroupBy.sum() function to the resulting
groups:
In [89]: df.groupby("A")[["C","D"]].sum()Out[89]: C DA bar 1.732707 1.073134foo 2.824590 -0.574779
Grouping by multiple columns label forms MultiIndex.
In [90]: df.groupby(["A","B"]).sum()Out[90]: C DA B bar one 1.511763 0.396823 three -0.990582 -0.532532 two 1.211526 1.208843foo one 1.614581 -1.658537 three 0.024580 -0.264610 two 1.185429 1.348368
In [91]: arrays=[ ....: ["bar","bar","baz","baz","foo","foo","qux","qux"], ....: ["one","two","one","two","one","two","one","two"], ....: ] ....: In [92]: index=pd.MultiIndex.from_arrays(arrays,names=["first","second"])In [93]: df=pd.DataFrame(np.random.randn(8,2),index=index,columns=["A","B"])In [94]: df2=df[:4]In [95]: df2Out[95]: A Bfirst second bar one -0.727965 -0.589346 two 0.339969 -0.693205baz one -0.339355 0.593616 two 0.884345 1.591431
The stack() method “compresses” a level in the DataFrame’s
columns:
In [96]: stacked=df2.stack(future_stack=True)In [97]: stackedOut[97]: first second bar one A -0.727965 B -0.589346 two A 0.339969 B -0.693205baz one A -0.339355 B 0.593616 two A 0.884345 B 1.591431dtype: float64
With a “stacked” DataFrame or Series (having a MultiIndex as the
index), the inverse operation of stack() is
unstack(), which by default unstacks the last level:
In [98]: stacked.unstack()Out[98]: A Bfirst second bar one -0.727965 -0.589346 two 0.339969 -0.693205baz one -0.339355 0.593616 two 0.884345 1.591431In [99]: stacked.unstack(1)Out[99]: second one twofirst bar A -0.727965 0.339969 B -0.589346 -0.693205baz A -0.339355 0.884345 B 0.593616 1.591431In [100]: stacked.unstack(
In [101]: df=pd.DataFrame( .....: { .....: "A":["one","one","two","three"]*3, .....: "B":["A"
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.
If you are attempting to perform a boolean operation on a Series or DataFrame
you might see an exception like:
In [141]: ifpd.Series([False,True,False]): .....: print("I was true") .....: ---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
<ipython-input-141-b27eb9c1dfc0> in ?()----> 1ifpd.Series([False,True,False]):2print("I was true")~/work/pandas/pandas/pandas/core/generic.py in ?(self)1578@final1579def__nonzero__(self)->NoReturn:-> 1580raiseValueError(1581f"The truth value of a {type(self).__name__} is ambiguous. "1582"Use a.empty, a.bool(), a.item(), a.any() or a.all()."1583)ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
For a DataFrame, passing a slice : selects matching rows:
In [25]: df[0:3]Out[25]: 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-03 -0.861849 -2.104569 -0.494929 1.071804In [26]: df["20130102":"20130104"]Out[26]: A B C D2013-01-02 1.212112 -0.173215 0.119209 -1.0442362013-01-03 -0.861849 -2.104569 -0.494929 1.0718042013-01-04 0.721555 -0.706771 -1.039575 0.271860
Selecting all rows (:) with a select column labels:
In [28]: df.loc[:,["A","B"]]Out[28]: A B2013-01-01 0.469112 -0.2828632013-01-02 1.212112 -0.1732152013-01-03 -0.861849 -2.1045692013-01-04 0.721555 -0.7067712013-01-05 -0.424972 0.5670202013-01-06 -0.673690 0.113648
For label slicing, both endpoints are included:
In [29]: df.loc["20130102":"20130104",["A","B"]]Out[29]: A B2013-01-02 1.212112 -0.1732152013-01-03 -0.861849 -2.1045692013-01-04 0.721555 -0.706771
Selecting a single row and column label returns a scalar:
In [30]: df.loc[dates[0],"A"]Out[30]: 0.4691122999071863
For getting fast access to a scalar (equivalent to the prior method):
In [31]: df.at[dates[0],"A"]Out[31]: 0.4691122999071863
Integer slices acts 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
Lists of integer position locations:
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.17321464905330858
For getting fast access to a scalar (equivalent to the prior method):
In [38]: df.iat[1,1]Out[38]: -0.17321464905330858
DataFrame
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 [103]: pd.pivot_table(df,values="D",index=["A","B"],columns=["C"])Out[103]: C bar fooA B one A 2.395985 -1.202872 B 1.395433 -1.814470 C -0.392670 -0.055224three A -0.595447 NaN B NaN 1.928123 C 0.166599 NaNtwo A NaN 0.007207 B 1.552825 NaN C NaN 1.018601