若定义:struct {int y, m, d;}int todayy, *pdata; 则为today

Essential Basic Functionality — pandas 0.19.0 documentation
Essential Basic Functionality
Here we discuss a lot of the essential functionality common to the pandas data
structures. Here’s how to create some of the objects used in the examples from
the previous section:
In [1]: index = pd.date_range('1/1/2000', periods=8)
In [2]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [3]: df = pd.DataFrame(np.random.randn(8, 3), index=index,
columns=['A', 'B', 'C'])
In [4]: wp = pd.Panel(np.random.randn(2, 5, 4), items=['Item1', 'Item2'],
major_axis=pd.date_range('1/1/2000', periods=5),
minor_axis=['A', 'B', 'C', 'D'])
Attributes and the raw ndarray(s)
pandas objects have a number of attributes enabling you to access the metadata
shape: gives the axis dimensions of the object, consistent with ndarray
Axis labels
Series: index (only axis)
DataFrame: index (rows) and columns
Panel: items, major_axis, and minor_axis
Note, these attributes can be safely assigned to!
In [8]: df[:2]
0...377312
0...011225
In [9]: df.columns = [x.lower() for x in df.columns]
In [10]: df
0...377312
0...011225
0...479010
-0...527750
-1...123836
0...823761
0...469725
1...203109
To get the actual data inside a data structure, one need only access the
values property:
In [11]: s.values
Out[11]: array([ 0.1122,
0.8717, -0.8161, -0.7849,
In [12]: df.values
array([[ 0.1875, -1.9339,
2.1416, -0.0112],
[ 0.0489, -1.3607, -0.479 ],
[-0.8597, -0.2316, -0.5278],
1.5556, -0.8238],
[ 0.5354, -1.0329,
In [13]: wp.values
array([[[-1.032 ,
0.9698, -0.9627,
0.6691, -0.4336, -0.2736],
[ 0.6804, -0.3084, -0.2761, -1.8212],
[-1.9936, -1.9274, -2.0279,
0.4553, -0.0307]],
[[ 0.9357,
1.0612, -2.1079,
[ 0.3236, -0.6416, -0.5875,
[ 0.1949, -0.382 ,
[-0.7283, -0.0903, -0.7482,
0.461 , -0.5427]]])
If a DataFrame or Panel contains homogeneously-typed data, the ndarray can
actually be modified in-place, and the changes will be reflected in the data
structure. For heterogeneous data (e.g. some of the DataFrame’s columns are not
all the same dtype), this will not be the case. The values attribute itself,
unlike the axis labels, cannot be assigned to.
When working with heterogeneous data, the dtype of the resulting ndarray
will be chosen to accommodate all of the data involved. For example, if
strings are involved, the result will be of object dtype. If there are only
floats and integers, the resulting array will be of float dtype.
Accelerated operations
pandas has support for accelerating certain types of binary numerical and boolean operations using
the numexpr library (starting in 0.11.0) and the bottleneck libraries.
These libraries are especially useful when dealing with large data sets, and provide large
speedups. numexpr uses smart chunking, caching, and multiple cores. bottleneck is
a set of specialized cython routines that are especially fast when dealing with arrays that have
Here is a sample (using 100 column x 100,000 row DataFrames):
You are highly encouraged to install both libraries. See the section
for more installation info.
Flexible binary operations
With binary operations between pandas data structures, there are two key points
of interest:
Broadcasting behavior between higher- (e.g. DataFrame) and
lower-dimensional (e.g. Series) objects.
Missing data in computations
We will demonstrate how to manage these issues independently, though they can
be handled simultaneously.
Matching / broadcasting behavior
DataFrame has the methods , ,
and related functions
for carrying out binary operations. For broadcasting behavior,
Series input is of primary interest. Using these functions, you can use to
either match on the index or columns via the axis keyword:
In [14]: df = pd.DataFrame({'one' : pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
'two' : pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
'three' : pd.Series(np.random.randn(3), index=['b', 'c', 'd'])})
In [15]: df
a -0.626544
NaN -0.351587
b -0...136249
0...448789
In [16]: row = df.ix[1]
In [17]: column = df['two']
In [18]: df.sub(row, axis='columns')
a -0.487650
NaN -1.487837
0...000000
0...585038
In [19]: df.sub(row, axis=1)
a -0.487650
NaN -1.487837
0...000000
0...585038
In [20]: df.sub(column, axis='index')
a -0.274957
In [21]: df.sub(column, axis=0)
a -0.274957
Furthermore you can align a level of a multi-indexed DataFrame with a Series.
In [22]: dfmi = df.copy()
In [23]: dfmi.index = pd.MultiIndex.from_tuples([(1,'a'),(1,'b'),(1,'c'),(2,'a')],
names=['first','second'])
In [24]: dfmi.sub(column, axis=0, level='second')
first second
-1...000000
0...000000
With Panel, describing the matching behavior is a bit more difficult, so
the arithmetic methods instead (and perhaps confusingly?) give you the option
to specify the broadcast axis. For example, suppose we wished to demean the
data over a particular axis. This can be accomplished by taking the mean over
an axis and broadcasting over the same axis:
In [25]: major_mean = wp.mean(axis='major')
In [26]: major_mean
A -0..260774
C -0..532794
In [27]: wp.sub(major_mean, axis='major')
&class 'pandas.core.panel.Panel'&
Dimensions: 2 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis:
00:00:00 to
Minor_axis axis: A to D
And similarly for axis=&items& and axis=&minor&.
I could be convinced to make the axis argument in the DataFrame methods
match the broadcasting behavior of Panel. Though it would require a
transition period so users can change their code...
Series and Index also support the
builtin. This function takes
the floor division and modulo operation at the same time returning a two-tuple
of the same type as the left hand side. For example:
In [28]: s = pd.Series(np.arange(10))
In [29]: s
dtype: int64
In [30]: div, rem = divmod(s, 3)
In [31]: div
dtype: int64
In [32]: rem
dtype: int64
In [33]: idx = pd.Index(np.arange(10))
In [34]: idx
Out[34]: Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')
In [35]: div, rem = divmod(idx, 3)
In [36]: div
Out[36]: Int64Index([0, 0, 0, 1, 1, 1, 2, 2, 2, 3], dtype='int64')
In [37]: rem
Out[37]: Int64Index([0, 1, 2, 0, 1, 2, 0, 1, 2, 0], dtype='int64')
We can also do elementwise :
In [38]: div, rem = divmod(s, [2, 2, 3, 3, 4, 4, 5, 5, 6, 6])
In [39]: div
dtype: int64
In [40]: rem
dtype: int64
Missing data / operations with fill values
In Series and DataFrame (though not yet in Panel), the arithmetic functions
have the option of inputting a fill_value, namely a value to substitute when
at most one of the values at a location are missing. For example, when adding
two DataFrame objects, you may wish to treat NaN as 0 unless both DataFrames
are missing that value, in which case the result will be NaN (you can later
replace NaN with some other value using fillna if you wish).
In [41]: df
a -0.626544
NaN -0.351587
b -0...136249
0...448789
In [42]: df2
a -0...351587
b -0...136249
0...448789
In [43]: df + df2
a -1.253088
NaN -0.703174
b -0...272499
0...897577
In [44]: df.add(df2, fill_value=0)
a -1...703174
b -0...272499
0...897577
Flexible Comparisons
Starting in v0.8, pandas introduced binary comparison methods eq, ne, lt, gt,
le, and ge to Series and DataFrame whose behavior is analogous to the binary
arithmetic operations described above:
In [45]: df.gt(df2)
In [46]: df2.ne(df)
These operations produce a pandas object the same type as the left-hand-side input
that if of dtype bool. These boolean objects can be used in indexing operations,
Boolean Reductions
You can apply the reductions: , ,
to provide a
way to summarize a boolean result.
In [47]: (df & 0).all()
dtype: bool
In [48]: (df & 0).any()
dtype: bool
You can reduce to a final boolean value.
In [49]: (df & 0).any().any()
Out[49]: True
You can test if a pandas object is empty, via the
In [50]: df.empty
Out[50]: False
In [51]: pd.DataFrame(columns=list('ABC')).empty
Out[51]: True
To evaluate single-element pandas objects in a boolean context, use the method
In [52]: pd.Series([True]).bool()
Out[52]: True
In [53]: pd.Series([False]).bool()
Out[53]: False
In [54]: pd.DataFrame([[True]]).bool()
Out[54]: True
In [55]: pd.DataFrame([[False]]).bool()
Out[55]: False
You might be tempted to do the following:
&&& if df:
&&& df and df2
These both will raise as you are trying to compare multiple values.
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
for a more detailed discussion.
Comparing if objects are equivalent
Often you may find there is more than one way to compute the same
As a simple example, consider df+df and df*2. To test
that these two computations produce the same result, given the tools
shown above, you might imagine using (df+df == df*2).all(). But in
fact, this expression is False:
In [56]: df+df == df*2
In [57]: (df+df == df*2).all()
dtype: bool
Notice that the boolean DataFrame df+df == df*2 contains some False values!
That is because NaNs do not compare as equals:
In [58]: np.nan == np.nan
Out[58]: False
So, as of v0.13.1, NDFrames (such as Series, DataFrames, and Panels)
method for testing equality, with NaNs in
corresponding locations treated as equal.
In [59]: (df+df).equals(df*2)
Out[59]: True
Note that the Series or DataFrame index needs to be in the same order for
equality to be True:
In [60]: df1 = pd.DataFrame({'col':['foo', 0, np.nan]})
In [61]: df2 = pd.DataFrame({'col':[np.nan, 0, 'foo']}, index=[2,1,0])
In [62]: df1.equals(df2)
Out[62]: False
In [63]: df1.equals(df2.sort_index())
Out[63]: True
Comparing array-like objects
You can conveniently do element-wise comparisons when comparing a pandas
data structure with a scalar value:
In [64]: pd.Series(['foo', 'bar', 'baz']) == 'foo'
dtype: bool
In [65]: pd.Index(['foo', 'bar', 'baz']) == 'foo'
Out[65]: array([ True, False, False], dtype=bool)
Pandas also handles element-wise comparisons between different array-like
objects of the same length:
In [66]: pd.Series(['foo', 'bar', 'baz']) == pd.Index(['foo', 'bar', 'qux'])
dtype: bool
In [67]: pd.Series(['foo', 'bar', 'baz']) == np.array(['foo', 'bar', 'qux'])
dtype: bool
Trying to compare Index or Series objects of different lengths will
raise a ValueError:
In [55]: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo', 'bar'])
ValueError: Series lengths must match to compare
In [56]: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo'])
ValueError: Series lengths must match to compare
Note that this is different from the numpy behavior where a comparison can
be broadcast:
In [68]: np.array([1, 2, 3]) == np.array([2])
Out[68]: array([False,
True, False], dtype=bool)
or it can return False if broadcasting can not be done:
In [69]: np.array([1, 2, 3]) == np.array([1, 2])
Out[69]: False
Combining overlapping data sets
A problem occasionally arising is the combination of two similar data sets
where values in one are preferred over the other. An example would be two data
series representing a particular economic indicator where one is considered to
be of “higher quality”. However, the lower quality series might extend further
back in history or have more complete data coverage. As such, we would like to
combine two DataFrame objects where missing values in one DataFrame are
conditionally filled with like-labeled values from the other DataFrame. The
function implementing this operation is ,
which we illustrate:
In [70]: df1 = pd.DataFrame({'A' : [1., np.nan, 3., 5., np.nan],
'B' : [np.nan, 2., 3., np.nan, 6.]})
In [71]: df2 = pd.DataFrame({'A' : [5., 2., 4., np.nan, 3., 7.],
'B' : [np.nan, np.nan, 3., 4., 6., 8.]})
In [72]: df1
In [73]: df2
In [74]: df1.combine_first(df2)
General DataFrame Combine
method above calls the more general
DataFrame method . This method takes another DataFrame
and a combiner function, aligns the input DataFrame and then passes the combiner
function pairs of Series (i.e., columns whose names are the same).
So, for instance, to reproduce
In [75]: combiner = lambda x, y: np.where(pd.isnull(x), y, x)
In [76]: df1.combine(df2, combiner)
Descriptive statistics
A large number of methods for computing descriptive statistics and other related
operations on , , and . Most of these
are aggregations (hence producing a lower-dimensional result) like
but some of them, like
produce an object of the same size. Generally speaking, these methods take an
axis argument, just like ndarray.{sum, std, ...}, but the axis can be
specified by name or integer:
Series: no axis argument needed
DataFrame: “index” (axis=0, default), “columns” (axis=1)
Panel: “items” (axis=0), “major” (axis=1, default), “minor”
For example:
In [77]: df
a -0.626544
NaN -0.351587
b -0...136249
0...448789
In [78]: df.mean(0)
dtype: float64
In [79]: df.mean(1)
dtype: float64
All such methods have a skipna option signaling whether to exclude missing
data (True by default):
In [80]: df.sum(0, skipna=False)
dtype: float64
In [81]: df.sum(axis=1, skipna=True)
dtype: float64
Combined with the broadcasting / arithmetic behavior, one can describe various
statistical procedures, like standardization (rendering data zero mean and
standard deviation 1), very concisely:
In [82]: ts_stand = (df - df.mean()) / df.std()
In [83]: ts_stand.std()
dtype: float64
In [84]: xs_stand = df.sub(df.mean(1), axis=0).div(df.std(1), axis=0)
In [85]: xs_stand.std(1)
dtype: float64
Note that methods like
preserve the location of NA values:
In [86]: df.cumsum()
a -0.626544
NaN -0.351587
b -0...784662
c -0...335874
Here is a quick reference summary table of common functions. Each also takes an
optional level parameter which applies only if the object has a
Number of non-null observations
Sum of values
Mean of values
Mean absolute deviation
Arithmetic median of values
Absolute Value
Product of values
Bessel-corrected sample standard deviation
Unbiased variance
Standard error of the mean
Sample skewness (3rd moment)
Sample kurtosis (4th moment)
Sample quantile (value at %)
Cumulative sum
Cumulative product
Cumulative maximum
Cumulative minimum
Note that by chance some NumPy methods, like mean, std, and sum,
will exclude NAs on Series input by default:
In [87]: np.mean(df['one'])
Out[87]: -0.3951
In [88]: np.mean(df['one'].values)
Out[88]: nan
Series also has a method
which will return the
number of unique non-null values:
In [89]: series = pd.Series(np.random.randn(500))
In [90]: series[20:500] = np.nan
In [91]: series[10:20]
In [92]: series.nunique()
Out[92]: 11
Summarizing data: describe
There is a convenient
function which computes a variety of summary
statistics about a Series or the columns of a DataFrame (excluding NAs of
In [93]: series = pd.Series(np.random.randn(1000))
In [94]: series[::2] = np.nan
In [95]: series.describe()
500.000000
dtype: float64
In [96]: frame = pd.DataFrame(np.random.randn(1000, 5), columns=['a', 'b', 'c', 'd', 'e'])
In [97]: frame.ix[::2] = np.nan
In [98]: frame.describe()
500.0.0.0.0.000000
You can select specific percentiles to include in the output:
In [99]: series.describe(percentiles=[.05, .25, .75, .95])
500.000000
dtype: float64
By default, the median is always included.
For a non-numerical Series object,
will give a simple
summary of the number of unique values and most frequently occurring values:
In [100]: s = pd.Series(['a', 'a', 'b', 'b', 'a', 'a', np.nan, 'c', 'd', 'a'])
In [101]: s.describe()
dtype: object
Note that on a mixed-type DataFrame object,
restrict the summary to include only numerical columns or, if none are, only
categorical columns:
In [102]: frame = pd.DataFrame({'a': ['Yes', 'Yes', 'No', 'No'], 'b': range(4)})
In [103]: frame.describe()
This behaviour can be controlled by providing a list of types as include/exclude
arguments. The special value all can also be used:
In [104]: frame.describe(include=['object'])
In [105]: frame.describe(include=['number'])
In [106]: frame.describe(include='all')
That feature relies on . Refer to
there for details about accepted inputs.
Index of Min/Max Values
functions on Series
and DataFrame compute the index labels with the minimum and maximum
corresponding values:
In [107]: s1 = pd.Series(np.random.randn(5))
In [108]: s1
dtype: float64
In [109]: s1.idxmin(), s1.idxmax()
Out[109]: (3, 1)
In [110]: df1 = pd.DataFrame(np.random.randn(5,3), columns=['A','B','C'])
In [111]: df1
0...169660
1...001988
2 -1...214583
0...207466
0...310515
In [112]: df1.idxmin(axis=0)
dtype: int64
In [113]: df1.idxmax(axis=1)
dtype: object
When there are multiple rows (or columns) matching the minimum or maximum
return the first
matching index:
In [114]: df3 = pd.DataFrame([2, 1, 1, 3, np.nan], columns=['A'], index=list('edcba'))
In [115]: df3
In [116]: df3['A'].idxmin()
Out[116]: 'd'
idxmin and idxmax are called argmin and argmax in NumPy.
Value counts (histogramming) / Mode
Series method and top-level function computes a histogram
of a 1D array of values. It can also be used as a function on regular arrays:
In [117]: data = np.random.randint(0, 7, size=50)
In [118]: data
array([5, 3, 2, 2, 1, 4, 0, 4, 0, 2, 0, 6, 4, 1, 6, 3, 3, 0, 2, 1, 0, 5, 5,
3, 6, 1, 5, 6, 2, 0, 0, 6, 3, 3, 5, 0, 4, 3, 3, 3, 0, 6, 1, 3, 5, 5,
0, 4, 0, 6])
In [119]: s = pd.Series(data)
In [120]: s.value_counts()
dtype: int64
In [121]: pd.value_counts(data)
dtype: int64
Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame:
In [122]: s5 = pd.Series([1, 1, 3, 3, 3, 5, 5, 7, 7, 7])
In [123]: s5.mode()
dtype: int64
In [124]: df5 = pd.DataFrame({&A&: np.random.randint(0, 7, size=50),
&B&: np.random.randint(-10, 15, size=50)})
In [125]: df5.mode()
Discretization and quantiling
Continuous values can be discretized using the
(bins based on values)
(bins based on sample quantiles) functions:
In [126]: arr = np.random.randn(20)
In [127]: factor = pd.cut(arr, 4)
In [128]: factor
[(-0.645, 0.336], (-2.61, -1.626], (-1.626, -0.645], (-1.626, -0.645], (-1.626, -0.645], ..., (0.336, 1.316], (0.336, 1.316], (0.336, 1.316], (0.336, 1.316], (-2.61, -1.626]]
Length: 20
Categories (4, object): [(-2.61, -1.626] & (-1.626, -0.645] & (-0.645, 0.336] & (0.336, 1.316]]
In [129]: factor = pd.cut(arr, [-5, -1, 0, 1, 5])
In [130]: factor
[(-1, 0], (-5, -1], (-1, 0], (-5, -1], (-1, 0], ..., (0, 1], (1, 5], (0, 1], (0, 1], (-5, -1]]
Length: 20
Categories (4, object): [(-5, -1] & (-1, 0] & (0, 1] & (1, 5]]
computes sample quantiles. For example, we could slice up some
normally distributed data into equal-size quartiles like so:
In [131]: arr = np.random.randn(30)
In [132]: factor = pd.qcut(arr, [0, .25, .5, .75, 1])
In [133]: factor
[(-0.139, 1.00736], (1.0], (1.0], [-1.0705, -0.439], [-1.0705, -0.439], ..., (1.0], [-1.0705, -0.439], (-0.439, -0.139], (-0.439, -0.139], (-0.439, -0.139]]
Length: 30
Categories (4, object): [[-1.0705, -0.439] & (-0.439, -0.139] & (-0.139, 1.00736] & (1.0]]
In [134]: pd.value_counts(factor)
[-1.0705, -0.439]
(-0.139, 1.00736]
(-0.439, -0.139]
dtype: int64
We can also pass infinite values to define the bins:
In [135]: arr = np.random.randn(20)
In [136]: factor = pd.cut(arr, [-np.inf, 0, np.inf])
In [137]: factor
[(-inf, 0], (0, inf], (0, inf], (0, inf], (-inf, 0], ..., (-inf, 0], (0, inf], (-inf, 0], (-inf, 0], (0, inf]]
Length: 20
Categories (2, object): [(-inf, 0] & (0, inf]]
Function application
To apply your own or another library’s functions to pandas objects,
you should be aware of the three methods below. The appropriate
method to use depends on whether your function expects to operate
on an entire DataFrame or Series, row- or column-wise, or elementwise.
function application:
Tablewise Function Application
New in version 0.16.2.
DataFrames and Series can of course just be passed into functions.
However, if the function needs to be called in a chain, consider using the
Compare the following
# f, g, and h are functions taking and returning ``DataFrames``
&&& f(g(h(df), arg1=1), arg2=2, arg3=3)
with the equivalent
&&& (df.pipe(h)
.pipe(g, arg1=1)
.pipe(f, arg2=2, arg3=3)
Pandas encourages the second style, which is known as method chaining.
pipe makes it easy to use your own or another library’s functions
in method chains, alongside pandas’ methods.
In the example above, the functions f, g, and h each expected the DataFrame as the first positional argument.
What if the function you wish to apply takes its data as, say, the second argument?
In this case, provide pipe with a tuple of (callable, data_keyword).
.pipe will route the DataFrame to the argument specified in the tuple.
For example, we can fit a regression using statsmodels. Their API expects a formula first and a DataFrame as the second argument, data. We pass in the function, keyword pair (sm.poisson, 'data') to pipe:
In [138]: import statsmodels.formula.api as sm
In [139]: bb = pd.read_csv('data/baseball.csv', index_col='id')
In [140]: (bb.query('h & 0')
.assign(ln_h = lambda df: np.log(df.h))
.pipe((sm.poisson, 'data'), 'hr ~ ln_h + year + g + C(lg)')
.summary()
Optimization terminated successfully.
Current function value: 2.116284
Iterations 24
&class 'statsmodels.iolib.summary.Summary'&
Poisson Regression Results
==============================================================================
Dep. Variable:
No. Observations:
Df Residuals:
Son, 02 Okt 2016
Pseudo R-squ.:
Log-Likelihood:
converged:
LLR p-value:
6.774e-136
===============================================================================
[95.0% Conf. Int.]
-------------------------------------------------------------------------------
C(lg)[T.NL]
===============================================================================
The pipe method is inspired by unix pipes and more recently
and , which
have introduced the popular (%&%) (read pipe) operator for .
The implementation of pipe here is quite clean and feels right at home in python.
We encourage you to view the source code (pd.DataFrame.pipe?? in IPython).
Row or Column-wise Function Application
Arbitrary functions can be applied along the axes of a DataFrame or Panel
method, which, like the descriptive
statistics methods, take an optional axis argument:
In [141]: df.apply(np.mean)
dtype: float64
In [142]: df.apply(np.mean, axis=1)
dtype: float64
In [143]: df.apply(lambda x: x.max() - x.min())
dtype: float64
In [144]: df.apply(np.cumsum)
a -0.626544
NaN -0.351587
b -0...784662
c -0...335874
In [145]: df.apply(np.exp)
0...115063
1...638401
Depending on the return type of the function passed to ,
the result will either be of lower dimension or the same dimension.
combined with some cleverness can be used to answer many questions
about a data set. For example, suppose we wanted to extract the date where the
maximum value for each column occurred:
In [146]: tsdf = pd.DataFrame(np.random.randn(1000, 3), columns=['A', 'B', 'C'],
index=pd.date_range('1/1/2000', periods=1000))
In [147]: tsdf.apply(lambda x: x.idxmax())
dtype: datetime64[ns]
You may also pass additional arguments and keyword arguments to the
method. For instance, consider the following function you would like to apply:
def subtract_and_divide(x, sub, divide=1):
return (x - sub) / divide
You may then apply this function as follows:
df.apply(subtract_and_divide, args=(5,), divide=3)
Another useful feature is the ability to pass Series methods to carry out some
Series operation on each column or row:
In [148]: tsdf
1...542846
-1...000884
-0...082042
-0...129646
-0...969004
0...150493
In [149]: tsdf.apply(pd.Series.interpolate)
1...542846
-1...000884
-0...082042
-0...039704
-0...002633
-0...044971
-0...087309
-0...129646
-0...969004
0...150493
takes an argument raw which is False by default, which
converts each row or column into a Series before applying the function. When
set to True, the passed function will instead receive an ndarray object, which
has positive performance implications if you do not need the indexing
functionality.
The section on
demonstrates related, flexible
functionality for grouping by some criterion, applying, and combining the
results into a Series, DataFrame, etc.
Applying elementwise Python functions
Since not all functions can be vectorized (accept NumPy arrays and return
another array or value), the methods
on DataFrame
and analogously
on Series accept any Python function taking
a single value and returning a single value. For example:
In [150]: df4
a -0.626544
NaN -0.351587
b -0...136249
0...448789
In [151]: f = lambda x: len(str(x))
In [152]: df4['one'].map(f)
Name: one, dtype: int64
In [153]: df4.applymap(f)
has an additional feature which is that it can be used to easily
“link” or “map” values defined by a secondary series. This is closely related
In [154]: s = pd.Series(['six', 'seven', 'six', 'seven', 'six'],
index=['a', 'b', 'c', 'd', 'e'])
In [155]: t = pd.Series({'six' : 6., 'seven' : 7.})
In [156]: s
dtype: object
In [157]: s.map(t)
dtype: float64
Applying with a Panel
Applying with a Panel will pass a Series to the applied function. If the applied
function returns a Series, the result of the application will be a Panel. If the applied function
reduces to a scalar, the result of the application will be a DataFrame.
Prior to 0.13.1 apply on a Panel would only work on ufuncs (e.g. np.sum/np.max).
In [158]: import pandas.util.testing as tm
In [159]: panel = tm.makePanel(5)
In [160]: panel
&class 'pandas.core.panel.Panel'&
Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis:
00:00:00 to
Minor_axis axis: A to D
In [161]: panel['ItemA']
0....528154
1....029371
0....631117
-0....172441
1....020485
A transformational apply.
In [162]: result = panel.apply(lambda x: x*2, axis='items')
In [163]: result
&class 'pandas.core.panel.Panel'&
Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis:
00:00:00 to
Minor_axis axis: A to D
In [164]: result['ItemA']
0....056308
3....058742
1....262234
-0....344882
2....040969
A reduction operation.
In [165]: panel.apply(lambda x: x.dtype, axis='items')
A similar reduction type operation
In [166]: panel.apply(lambda x: x.sum(), axis='major_axis')
3...840809
3...114512
5...431906
D -1...857043
This last reduction is equivalent to
In [167]: panel.sum('major_axis')
3...840809
3...114512
5...431906
D -1...857043
A transformation operation that returns a Panel, but is computing
the z-score across the major_axis.
In [168]: result = panel.apply(
lambda x: (x-x.mean())/x.std(),
axis='major_axis')
In [169]: result
&class 'pandas.core.panel.Panel'&
Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
Items axis: ItemA to ItemC
Major_axis axis:
00:00:00 to
Minor_axis axis: A to D
In [170]: result['ItemA']
-0....341731
1....398661
-0....619210
-1....156654
0....277837
Apply can also accept multiple axes in the axis argument. This will pass a
DataFrame of the cross-section to the applied function.
In [171]: f = lambda x: ((x.T-x.mean(1))/x.std(1)).T
In [172]: result = panel.apply(f, axis = ['items','major_axis'])
In [173]: result
&class 'pandas.core.panel.Panel'&
Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
Items axis: A to D
Major_axis axis:
00:00:00 to
Minor_axis axis: ItemA to ItemC
In [174]: result.loc[:,:,'ItemA']
0....575106
0....070674
-0....051477
-0....043602
1....891680
This is equivalent to the following
In [175]: result = pd.Panel(dict([ (ax, f(panel.loc[:,:,ax]))
for ax in panel.minor_axis ]))
In [176]: result
&class 'pandas.core.panel.Panel'&
Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
Items axis: A to D
Major_axis axis:
00:00:00 to
Minor_axis axis: ItemA to ItemC
In [177]: result.loc[:,:,'ItemA']
0....575106
0....070674
-0....051477
-0....043602
1....891680
Reindexing and altering labels
is the fundamental data alignment method in pandas.
It is used to implement nearly all other features relying on label-alignment
functionality. To reindex means to conform the data to match a given set of
labels along a particular axis. This accomplishes several things:
Reorders the existing data to match a new set of labels
Inserts missing value (NA) markers in label locations where no data for
that label existed
If specified, fill data for missing labels using logic (highly relevant
to working with time series data)
Here is a simple example:
In [178]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [179]: s
dtype: float64
In [180]: s.reindex(['e', 'b', 'f', 'd'])
dtype: float64
Here, the f label was not contained in the Series and hence appears as
NaN in the result.
With a DataFrame, you can simultaneously reindex the index and columns:
In [181]: df
a -0.626544
NaN -0.351587
b -0...136249
0...448789
In [182]: df.reindex(index=['c', 'f', 'b'], columns=['three', 'two', 'one'])
0...011617
b -0...138894
For convenience, you may utilize the
method, which
takes the labels and a keyword axis parameter.
Note that the Index objects containing the actual axis labels can be
shared between objects. So if we have a Series and a DataFrame, the
following can be done:
In [183]: rs = s.reindex(df.index)
In [184]: rs
dtype: float64
In [185]: rs.index is df.index
Out[185]: True
This means that the reindexed Series’s index is the same Python object as the
DataFrame’s index.
is an even more concise way of
doing reindexing.
When writing performance-sensitive code, there is a good reason to spend
some time becoming a reindexing ninja: many operations are faster on
pre-aligned data. Adding two unaligned DataFrames internally triggers a
reindexing step. For exploratory analysis you will hardly notice the
difference (because reindex has been heavily optimized), but when CPU
cycles matter sprinkling a few explicit reindex calls here and there can
have an impact.
Reindexing to align with another object
You may wish to take an object and reindex its axes to be labeled the same as
another object. While the syntax for this is straightforward albeit verbose, it
is a common enough operation that the
available to make this simpler:
In [186]: df2
a -0..351587
b -0..136249
In [187]: df3
a -0..463545
In [188]: df.reindex_like(df2)
a -0..351587
b -0..136249
Aligning objects with each other with align
method is the fastest way to simultaneously align two objects. It
supports a join argument (related to ):
join='outer': take the union of the indexes (default)
join='left': use the calling object’s index
join='right': use the passed object’s index
join='inner': intersect the indexes
It returns a tuple with both of the reindexed Series:
In [189]: s = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e'])
In [190]: s1 = s[:4]
In [191]: s2 = s[1:]
In [192]: s1.align(s2)
dtype: float64, a
dtype: float64)
In [193]: s1.align(s2, join='inner')
dtype: float64, b
dtype: float64)
In [194]: s1.align(s2, join='left')
dtype: float64, a
dtype: float64)
For DataFrames, the join method will be applied to both the index and the
columns by default:
In [195]: df.align(df2, join='inner')
a -0..351587
b -0..136249
0..448789,
a -0..351587
b -0..136249
0..448789)
You can also pass an axis option to only align on the specified axis:
In [196]: df.align(df2, join='inner', axis=0)
a -0.626544
NaN -0.351587
b -0...136249
0...448789,
a -0..351587
b -0..136249
0..448789)
If you pass a Series to , you can choose to align both
objects either on the DataFrame’s index or columns using the axis argument:
In [197]: df.align(df2.ix[0], axis=1)
a -0.626544
NaN -0.351587
b -0...136249
0...448789
1..101558, one
Name: a, dtype: float64)
Filling while reindexing
takes an optional parameter method which is a
filling method chosen from the following table:
pad / ffill
Fill values forward
bfill / backfill
Fill values backward
Fill from the nearest index value
We illustrate these fill methods on a simple Series:
In [198]: rng = pd.date_range('1/3/2000', periods=8)
In [199]: ts = pd.Series(np.random.randn(8), index=rng)
In [200]: ts2 = ts[[0, 3, 6]]
In [201]: ts
Freq: D, dtype: float64
In [202]: ts2
dtype: float64
In [203]: ts2.reindex(ts.index)
Freq: D, dtype: float64
In [204]: ts2.reindex(ts.index, method='ffill')
Freq: D, dtype: float64
In [205]: ts2.reindex(ts.index, method='bfill')
Freq: D, dtype: float64
In [206]: ts2.reindex(ts.index, method='nearest')
Freq: D, dtype: float64
These methods require that the indexes are ordered increasing or
decreasing.
Note that the same result could have been achieved using
(except for method='nearest') or
In [207]: ts2.reindex(ts.index).fillna(method='ffill')
Freq: D, dtype: float64
will raise a ValueError if the index is not monotonic
increasing or decreasing.
will not make any checks on the order of the index.
Limits on filling while reindexing
The limit and tolerance arguments provide additional control over
filling while reindexing. Limit specifies the maximum count of consecutive
In [208]: ts2.reindex(ts.index, method='ffill', limit=1)
Freq: D, dtype: float64
In contrast, tolerance specifies the maximum distance between the index and
indexer values:
In [209]: ts2.reindex(ts.index, method='ffill', tolerance='1 day')
Freq: D, dtype: float64
Notice that when used on a DatetimeIndex, TimedeltaIndex or
PeriodIndex, tolerance will coerced into a Timedelta if possible.
This allows you to specify tolerance with appropriate strings.
Dropping labels from an axis
A method closely related to reindex is the
It removes a set of labels from an axis:
In [210]: df
a -0.626544
NaN -0.351587
b -0...136249
0...448789
In [211]: df.drop(['a', 'd'], axis=0)
b -0...136249
0...448789
In [212]: df.drop(['one'], axis=1)
NaN -0.351587
b -0..136249
Note that the following also works, but is a bit less obvious / clean:
In [213]: df.reindex(df.index.difference(['a', 'd']))
b -0...136249
0...448789
Renaming / mapping labels
method allows you to relabel an axis based on some
mapping (a dict or Series) or an arbitrary function.
In [214]: s
dtype: float64
In [215]: s.rename(str.upper)
dtype: float64
If you pass a function, it must return a value when called with any of the
labels (and must produce a set of unique values). A dict or
Series can also be used:
In [216]: df.rename(columns={'one' : 'foo', 'two' : 'bar'},
index={'a' : 'apple', 'b' : 'banana', 'd' : 'durian'})
NaN -0.351587
banana -0...136249
0...448789
If the mapping doesn’t include a column/index label, it isn’t renamed. Also
extra labels in the mapping don’t throw an error.
method also provides an inplace named
parameter that is by default False and copies the underlying data. Pass
inplace=True to rename the data in place.
New in version 0.18.0.
also accepts a scalar or list-like
for altering the Series.name attribute.
In [217]: s.rename(&scalar-name&)
Name: scalar-name, dtype: float64
The Panel class has a related
class which can rename
any of its three axes.
The behavior of basic iteration over pandas objects depends on the type.
When iterating over a Series, it is regarded as array-like, and basic iteration
produces the values. Other data structures, like DataFrame and Panel,
follow the dict-like convention of iterating over the “keys” of the
In short, basic iteration (for i in object) produces:
Series: values
DataFrame: column labels
Panel: item labels
Thus, for example, iterating over a DataFrame gives you the column names:
In [218]: df = pd.DataFrame({'col1' : np.random.randn(3), 'col2' : np.random.randn(3)},
index=['a', 'b', 'c'])
In [219]: for col in df:
print(col)
Pandas objects also have the dict-like
iterate over the (key, value) pairs.
To iterate over the rows of a DataFrame, you can use the following methods:
: Iterate over the rows of a DataFrame as (index, Series) pairs.
This converts the rows to Series objects, which can change the dtypes and has some
performance implications.
: Iterate over the rows of a DataFrame
as namedtuples of the values.
This is a lot faster than
, and is in most cases preferable to use
to iterate over the values of a DataFrame.
Iterating through pandas objects is generally slow. In many cases,
iterating manually over the rows is not needed and can be avoided with
one of the following approaches:
Look for a vectorized solution: many operations can be performed using
built-in methods or numpy functions, (boolean) indexing, ...
When you have a function that cannot work on the full DataFrame/Series
at once, it is better to use
instead of iterating
over the values. See the docs on .
If you need to do iterative manipulations on the values but performance is
important, consider writing the inner loop using e.g. cython or numba.
section for some
examples of this approach.
You should never modify something you are iterating over.
This is not guaranteed to work in all cases. Depending on the
data types, the iterator returns a copy and not a view, and writing
to it will have no effect!
For example, in the following case setting the value has no effect:
In [220]: df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']})
In [221]: for index, row in df.iterrows():
row['a'] = 10
In [222]: df
Consistent with the dict-like interface,
through key-value pairs:
Series: (index, scalar value) pairs
DataFrame: (column, Series) pairs
Panel: (item, DataFrame) pairs
For example:
In [223]: for item, frame in wp.iteritems():
print(item)
print(frame)
-1....382083
-0....273610
0....821168
-1....624972
0....030740
0....199905
0....053897
0....089075
-0....318931
-2....542749
allows you to iterate through the rows of a
DataFrame as Series objects. It returns an iterator yielding each
index value along with a Series containing the data in each row:
In [224]: for row_index, row in df.iterrows():
print('%s\n%s' % (row_index, row))
Name: 0, dtype: object
Name: 1, dtype: object
Name: 2, dtype: object
returns a Series for each row,
it does not preserve dtypes across the rows (dtypes are
preserved across columns for DataFrames). For example,
In [225]: df_orig = pd.DataFrame([[1, 1.5]], columns=['int', 'float'])
In [226]: df_orig.dtypes
dtype: object
In [227]: row = next(df_orig.iterrows())[1]
In [228]: row
Name: 0, dtype: float64
All values in row, returned as a Series, are now upcasted
to floats, also the original integer value in column x:
In [229]: row['int'].dtype
Out[229]: dtype('float64')
In [230]: df_orig['int'].dtype
Out[230]: dtype('int64')
To preserve dtypes while iterating over the rows, it is better
which returns namedtuples of the values
and which is generally much faster as iterrows.
For instance, a contrived way to transpose the DataFrame would be:
In [231]: df2 = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
In [232]: print(df2)
In [233]: print(df2.T)
In [234]: df2_t = pd.DataFrame(dict((idx,values) for idx, values in df2.iterrows()))
In [235]: print(df2_t)
itertuples
method will return an iterator
yielding a namedtuple for each row in the DataFrame. The first element
of the tuple will be the row’s corresponding index value, while the
remaining values are the row values.
For instance,
In [236]: for row in df.itertuples():
print(row)
Pandas(Index=0, a=1, b='a')
Pandas(Index=1, a=2, b='b')
Pandas(Index=2, a=3, b='c')
This method does not convert the row to a Series object but just
returns the values inside a namedtuple. Therefore,
preserves the data type of the values
and is generally faster as .
The column names will be renamed to positional names if they are
invalid Python identifiers, repeated, or start with an underscore.
With a large number of columns (&255), regular tuples are returned.
.dt accessor
Series has an accessor to succinctly return datetime like properties for the
values of the Series, if it is a datetime/period like Series.
This will return a Series, indexed like the existing Series.
# datetime
In [237]: s = pd.Series(pd.date_range(':10:12', periods=4))
In [238]: s
dtype: datetime64[ns]
In [239]: s.dt.hour
dtype: int64
In [240]: s.dt.second
dtype: int64
In [241]: s.dt.day
dtype: int64
This enables nice expressions like this:
In [242]: s[s.dt.day==2]
dtype: datetime64[ns]
You can easily produces tz aware transformations:
In [243]: stz = s.dt.tz_localize('US/Eastern')
In [244]: stz
09:10:12-05:00
09:10:12-05:00
09:10:12-05:00
09:10:12-05:00
dtype: datetime64[ns, US/Eastern]
In [245]: stz.dt.tz
Out[245]: &DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD&
You can also chain these types of operations:
In [246]: s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
04:10:12-05:00
04:10:12-05:00
04:10:12-05:00
04:10:12-05:00
dtype: datetime64[ns, US/Eastern]
You can also format datetime values as strings with
supports the same format as the standard .
# DatetimeIndex
In [247]: s = pd.Series(pd.date_range(';, periods=4))
In [248]: s
dtype: datetime64[ns]
In [249]: s.dt.strftime('%Y/%m/%d')
dtype: object
# PeriodIndex
In [250]: s = pd.Series(pd.period_range(';, periods=4))
In [251]: s
dtype: object
In [252]: s.dt.strftime('%Y/%m/%d')
dtype: object
The .dt accessor works for period and timedelta dtypes.
In [253]: s = pd.Series(pd.period_range(';, periods=4, freq='D'))
In [254]: s
dtype: object
In [255]: s.dt.year
dtype: int64
In [256]: s.dt.day
dtype: int64
# timedelta
In [257]: s = pd.Series(pd.timedelta_range('1 day 00:00:05', periods=4, freq='s'))
In [258]: s
1 days 00:00:05
1 days 00:00:06
1 days 00:00:07
1 days 00:00:08
dtype: timedelta64[ns]
In [259]: s.dt.days
dtype: int64
In [260]: s.dt.seconds
dtype: int64
In [261]: s.dt.components
milliseconds
microseconds
nanoseconds
Series.dt will raise a TypeError if you access with a non-datetimelike values
Vectorized string methods
Series is equipped with a set of string processing methods that make it easy to
operate on each element of the array. Perhaps most importantly, these methods
exclude missing/NA values automatically. These are accessed via the Series’s
str attribute and generally have names matching the equivalent (scalar)
built-in string methods. For example:
In [262]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
In [263]: s.str.lower()
dtype: object
Powerful pattern-matching methods are provided as well, but note that
pattern-matching generally uses
by default (and in some cases
always uses them).
Please see
for a complete
description.
The sorting API is substantially changed in 0.17.0, see
for these changes.
In particular, all sorting methods now return a new object by default, and DO NOT operate in-place (except by passing inplace=True).
There are two obvious kinds of sorting that you may be interested in: sorting
by label and sorting by actual values.
The primary method for sorting axis
labels (indexes) are the Series.sort_index() and the DataFrame.sort_index() methods.
In [264]: unsorted_df = df.reindex(index=['a', 'd', 'c', 'b'],
columns=['three', 'two', 'one'])
# DataFrame
In [265]: unsorted_df.sort_index()
In [266]: unsorted_df.sort_index(ascending=False)
In [267]: unsorted_df.sort_index(axis=1)
In [268]: unsorted_df['three'].sort_index()
Name: three, dtype: float64
are the entry points for value sorting (that is the values in a column or row).
can accept an optional by argument for axis=0
which will use an arbitrary vector or a column name of the DataFrame to
determine the sort order:
In [269]: df1 = pd.DataFrame({'one':[2,1,1,1],'two':[1,3,2,4],'three':[5,4,3,2]})
In [270]: df1.sort_values(by='two')
The by argument can take a list of column names, e.g.:
In [271]: df1[['one', 'two', 'three']].sort_values(by=['one','two'])
These methods have special treatment of NA values via the na_position
In [272]: s[2] = np.nan
In [273]: s.sort_values()
dtype: object
In [274]: s.sort_values(na_position='first')
dtype: object
smallest / largest values
New in version 0.14.0.
Series has the
methods which return the
smallest or largest n values. For a large Series this can be much
faster than sorting the entire Series and calling head(n) on the result.
In [282]: s = pd.Series(np.random.permutation(10))
In [283]: s
dtype: int64
In [284]: s.sort_values()
dtype: int64
In [285]: s.nsmallest(3)
dtype: int64
In [286]: s.nlargest(3)
dtype: int64
New in version 0.17.0.
DataFrame also has the nlargest and nsmallest methods.
In [287]: df = pd.DataFrame({'a': [-2, -1, 1, 10, 8, 11, -1],
'b': list('abdceff'),
'c': [1.0, 2.0, 4.0, 3.2, np.nan, 3.0, 4.0]})
In [288]: df.nlargest(3, 'a')
In [289]: df.nlargest(5, ['a', 'c'])
In [290]: df.nsmallest(3, 'a')
In [291]: df.nsmallest(5, ['a', 'c'])
Sorting by a multi-index column
You must be explicit about sorting when the column is a multi-index, and fully specify
all levels to by.
In [292]: df1.columns = pd.MultiIndex.from_tuples([('a','one'),('a','two'),('b','three')])
In [293]: df1.sort_values(by=('a','two'))
one two three
method on pandas objects copies the underlying data (though not
the axis indexes, since they are immutable) and returns a new object. Note that
it is seldom necessary to copy objects. For example, there are only a
handful of ways to alter a DataFrame in-place:
Inserting, deleting, or modifying a column
Assigning to the index or columns attributes
For homogeneous data, directly modifying the values via the values
attribute or advanced indexing
To be clear, no pandas methods have the side effect of
almost all methods return new objects, leaving the original object
untouched. If data is modified, it is because you did so explicitly.
The main types stored in pandas objects are float, int, bool,
datetime64[ns] and datetime64[ns, tz] (in &= 0.17.0), timedelta[ns], category (in &= 0.15.0), and object. In addition these dtypes
have item sizes, e.g. int64 and int32. See
for more detail on datetime64[ns, tz] dtypes.
A convenient
attribute for DataFrames returns a Series with the data type of each column.
In [294]: dft = pd.DataFrame(dict(A = np.random.rand(3),
C = 'foo',
D = pd.Timestamp(';),
E = pd.Series([1.0]*3).astype('float32'),
F = False,
G = pd.Series([1]*3,dtype='int8')))
In [295]: dft
In [296]: dft.dtypes
datetime64[ns]
dtype: object
On a Series use the
attribute.
In [297]: dft['A'].dtype
Out[297]: dtype('float64')
If a pandas object contains data multiple dtypes IN A SINGLE COLUMN, the dtype of the
column will be chosen to accommodate all of the data types (object is the most
# these ints are coerced to floats
In [298]: pd.Series([1, 2, 3, 4, 5, 6.])
dtype: float64
# string data forces an ``object`` dtype
In [299]: pd.Series([1, 2, 3, 6., 'foo'])
dtype: object
The method
will return the number of columns of
each type in a DataFrame:
In [300]: dft.get_dtype_counts()
datetime64[ns]
dtype: int64
Numeric dtypes will propagate and can coexist in DataFrames (starting in v0.11.0).
If a dtype is passed (either directly via the dtype keyword, a passed ndarray,
or a passed Series, then it will be preserved in DataFrame operations. Furthermore,
different numeric dtypes will NOT be combined. The following example will give you a taste.
In [301]: df1 = pd.DataFrame(np.random.randn(8, 1), columns=['A'], dtype='float32')
In [302]: df1
3 -1.543048
4 -0.123256
6 -0.143778
7 -2.885090
In [303]: df1.dtypes
dtype: object
In [304]: df2 = pd.DataFrame(dict( A = pd.Series(np.random.randn(8), dtype='float16'),
B = pd.Series(np.random.randn(8)),
C = pd.Series(np.array(np.random.randn(8), dtype='uint8')) ))
In [305]: df2
3 -0..950661
4 -1..087527
5 -0..339212
In [306]: df2.dtypes
dtype: object
By default integer types are int64 and float types are float64,
REGARDLESS of platform (32-bit or 64-bit). The following will all result in int64 dtypes.
In [307]: pd.DataFrame([1, 2], columns=['a']).dtypes
dtype: object
In [308]: pd.DataFrame({'a': [1, 2]}).dtypes
dtype: object
In [309]: pd.DataFrame({'a': 1 }, index=list(range(2))).dtypes
dtype: object
Numpy, however will choose platform-dependent types when creating arrays.
The following WILL result in int32 on 32-bit platform.
In [310]: frame = pd.DataFrame(np.array([1, 2]))
Types can potentially be upcasted when combined with other types, meaning they are promoted
from the current type (say int to float)
In [311]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2
In [312]: df3
3 -1..950661
4 -1..087527
7 -2..775379
In [313]: df3.dtypes
dtype: object
The values attribute on a DataFrame return the lower-common-denominator of the dtypes, meaning
the dtype that can accommodate ALL of the types in the resulting homogeneous dtyped numpy array. This can
force some upcasting.
In [314]: df3.values.dtype
Out[314]: dtype('float64')
You can use the
method to explicitly convert dtypes from one to another. These will by default return a copy,
even if the dtype was unchanged (pass copy=False to change this behavior). In addition, they will raise an
exception if the astype operation is invalid.
Upcasting is always according to the numpy rules. If two different dtypes are involved in an operation,
then the more general one will be used as the result of the operation.
In [315]: df3
3 -1..950661
4 -1..087527
7 -2..775379
In [316]: df3.dtypes
dtype: object
# conversion of dtypes
In [317]: df3.astype('float32').dtypes
dtype: object
Convert a subset of columns to a specified type using
In [318]: dft = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
In [319]: dft[['a','b']] = dft[['a','b']].astype(np.uint8)
In [320]: dft
In [321]: dft.dtypes
dtype: object
When trying to convert a subset of columns to a specified type using
and , upcasting occurs.
tries to fit in what we are assigning to the current dtypes, while [] will overwrite them taking the dtype from the right hand side. Therefore the following piece of code produces the unintended result.
In [322]: dft = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [7, 8, 9]})
In [323]: dft.loc[:, ['a', 'b']].astype(np.uint8).dtypes
dtype: object
In [324]: dft.loc[:, ['a', 'b']] = dft.loc[:, ['a', 'b']].astype(np.uint8)
In [325]: dft.dtypes
dtype: object
object conversion
pandas offers various functions to try to force conversion of types from the object dtype to other types.
The following functions are available for one dimensional object arrays or scalars:
(conversion to numeric dtypes)
In [326]: m = ['1.1', 2, 3]
In [327]: pd.to_numeric(m)
Out[327]: array([ 1.1,
(conversion to datetime objects)
In [328]: import datetime
In [329]: m = ['', datetime.datetime(2016, 3, 2)]
In [330]: pd.to_datetime(m)
Out[330]: DatetimeIndex(['', ''], dtype='datetime64[ns]', freq=None)
(conversion to timedelta objects)
In [331]: m = ['5us', pd.Timedelta('1day')]
In [332]: pd.to_timedelta(m)
Out[332]: TimedeltaIndex(['0 days 00:00:00.;, '1 days 00:00:00'], dtype='timedelta64[ns]', freq=None)
To force a conversion, we can pass in an errors argument, which specifies how pandas should deal with elements
that cannot be converted to desired dtype or object. By default, errors='raise', meaning that any errors encountered
will be raised during the conversion process. However, if errors='coerce', these errors will be ignored and pandas
will convert problematic elements to pd.NaT (for datetime and timedelta) or np.nan (for numeric). This might be
useful if you are reading in data which is mostly of the desired dtype (e.g. numeric, datetime), but occasionally has
non-conforming elements intermixed that you want to represent as missing:
In [333]: import datetime
In [334]: m = ['apple', datetime.datetime(2016, 3, 2)]
In [335]: pd.to_datetime(m, errors='coerce')
Out[335]: DatetimeIndex(['NaT', ''], dtype='datetime64[ns]', freq=None)
In [336]: m = ['apple', 2, 3]
In [337]: pd.to_numeric(m, errors='coerce')
Out[337]: array([ nan,
In [338]: m = ['apple', pd.Timedelta('1day')]
In [339]: pd.to_timedelta(m, errors='coerce')
Out[339]: TimedeltaIndex([NaT, '1 days'], dtype='timedelta64[ns]', freq=None)
The errors parameter has a third option of errors='ignore', which will simply return the passed in data if it
encounters any errors with the conversion to a desired data type:
In [340]: import datetime
In [341]: m = ['apple', datetime.datetime(2016, 3, 2)]
In [342]: pd.to_datetime(m, errors='ignore')
Out[342]: array(['apple', datetime.datetime(2016, 3, 2, 0, 0)], dtype=object)
In [343]: m = ['apple', 2, 3]
In [344]: pd.to_numeric(m, errors='ignore')
Out[344]: array(['apple', 2, 3], dtype=object)
In [345]: m = ['apple', pd.Timedelta('1day')]
In [346]: pd.to_timedelta(m, errors='ignore')
Out[346]: array(['apple', Timedelta('1 days 00:00:00')], dtype=object)
In addition to object conversion,
provides another argument downcast, which gives the
option of downcasting the newly (or already) numeric data to a smaller dtype, which can conserve memory:
In [347]: m = ['1', 2, 3]
In [348]: pd.to_numeric(m, downcast='integer')
# smallest signed int dtype
Out[348]: array([1, 2, 3], dtype=int8)
In [349]: pd.to_numeric(m, downcast='signed')
# same as 'integer'
Out[349]: array([1, 2, 3], dtype=int8)
In [350]: pd.to_numeric(m, downcast='unsigned')
# smallest unsigned int dtype
Out[350]: array([1, 2, 3], dtype=uint8)
In [351]: pd.to_numeric(m, downcast='float')
# smallest float dtype
Out[351]: array([ 1.,
3.], dtype=float32)
As these methods apply only to one-dimensional arrays, they cannot be used directly on multi-dimensional objects such
as DataFrames. However, with , we can “apply” the function over each column efficiently:
In [352]: import datetime
In [353]: df = pd.DataFrame([['', datetime.datetime(2016, 3, 2)]] * 2, dtype='O')
In [354]: df
In [355]: df.apply(pd.to_datetime)
In [356]: df = pd.DataFrame([['1.1', 2, 3]] * 2, dtype='O')
In [357]: df
In [358]: df.apply(pd.to_numeric)
In [359]: df = pd.DataFrame([['5us', pd.Timedelta('1day')]] * 2, dtype='O')
In [360]: df
1 days 00:00:00
1 days 00:00:00
In [361]: df.apply(pd.to_timedelta)
0 00:00:00. days
1 00:00:00. days
Performing selection operations on integer type data can easily upcast the data to floating.
The dtype of the input data will be preserved in cases where nans are not introduced (starting in 0.11.0)
In [362]: dfi = df3.astype('int32')
In [363]: dfi['E'] = 1
In [364]: dfi
In [365]: dfi.dtypes
dtype: object
In [366]: casted = dfi[dfi&0]
In [367]: casted
In [368]: casted.dtypes
dtype: object
While float dtypes are unchanged.
In [369]: dfa = df3.copy()
In [370]: dfa['A'] = dfa['A'].astype('float32')
In [371]: dfa.dtypes
dtype: object
In [372]: casted = dfa[df2&0]
In [373]: casted
7 -2..775379
In [374]: casted.dtypes
dtype: object
Selecting columns based on dtype
New in version 0.14.1.
method implements subsetting of columns
based on their dtype.
First, let’s create a
with a slew of different
In [375]: df = pd.DataFrame({'string': list('abc'),
'int64': list(range(1, 4)),
'uint8': np.arange(3, 6).astype('u1'),
'float64': np.arange(4.0, 7.0),
'bool1': [True, False, True],
'bool2': [False, True, False],
'dates': pd.date_range('now', periods=3).values,
'category': pd.Series(list(&ABC&)).astype('category')})
In [376]: df['tdeltas'] = df.dates.diff()
In [377]: df['uint64'] = np.arange(3, 6).astype('u8')
In [378]: df['other_dates'] = pd.date_range(';, periods=3).values
In [379]: df['tz_aware_dates'] = pd.date_range(';, periods=3, tz='US/Eastern')
In [380]: df
bool2 category
int64 string
16:19:24.826303
16:19:24.826303
16:19:24.826303
uint64 other_dates
tz_aware_dates
00:00:00-05:00
00:00:00-05:00
00:00:00-05:00
And the dtypes
In [381]: df.dtypes
datetime64[ns]
timedelta64[ns]
other_dates
datetime64[ns]
tz_aware_dates
datetime64[ns, US/Eastern]
dtype: object
has two parameters include and exclude that allow you to
say “give me the columns WITH these dtypes” (include) and/or “give the
columns WITHOUT these dtypes” (exclude).
For example, to select bool columns
In [382]: df.select_dtypes(include=[bool])
You can also pass the name of a dtype in the :
In [383]: df.select_dtypes(include=['bool'])
also works with generic dtypes as well.
For example, to select all numeric and boolean columns while excluding unsigned
In [384]: df.select_dtypes(include=['number', 'bool'], exclude=['unsignedinteger'])
To select string columns you must use the object dtype:
In [385]: df.select_dtypes(include=['object'])
To see all the child dtypes of a generic dtype like numpy.number you
can define a function that returns a tree of child dtypes:
In [386]: def subdtypes(dtype):
subs = dtype.__subclasses__()
if not subs:
return dtype
return [dtype, [subdtypes(dt) for dt in subs]]
All numpy dtypes are subclasses of numpy.generic:
In [387]: subdtypes(np.generic)
[numpy.generic,
[[numpy.number,
[[numpy.integer,
[[numpy.signedinteger,
[numpy.int8,
numpy.int16,
numpy.int32,
numpy.int64,
numpy.int64,
numpy.timedelta64]],
[numpy.unsignedinteger,
[numpy.uint8,
numpy.uint16,
numpy.uint32,
numpy.uint64,
numpy.uint64]]]],
[numpy.inexact,
[[numpy.floating,
[numpy.float16, numpy.float32, numpy.float64, numpy.float128]],
[plexfloating,
[plex64, plex128, plex256]]]]]],
[numpy.flexible,
[[numpy.character, [numpy.string_, numpy.unicode_]],
[numpy.void, [numpy.record]]]],
numpy.bool_,
numpy.datetime64,
numpy.object_]]
Pandas also defines the types category, and datetime64[ns, tz], which are not integrated into the normal
numpy hierarchy and wont show up with the above function.
The include and exclude parameters must be non-string sequences.

我要回帖

更多关于 pdata gpio 的文章

 

随机推荐