C:\Ana\lib\site-packages\IPython\core\interactiveshell.py:3267: FutureWarning:
Panel is deprecated and will be removed in a future version.
The recommended way to represent these types of 3-dimensional data are with a MultiIndex on a DataFrame, via the Panel.to_frame() method
Alternatively, you can use the xarray package http://xarray.pydata.org/en/stable/.
Pandas provides a `.to_xarray()` method to help automate this conversion.
exec(code_obj, self.user_global_ns, self.user_ns)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 5 (minor_axis)
Items axis: 0 to 1
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 4
data = 'Item1' : pd.DataFrame(np.random.randn(4, 3)),
'Item2' : pd.DataFrame(np.random.randn(4, 2))
p = pd.Panel(data)
p
C:\Ana\lib\site-packages\IPython\core\interactiveshell.py:3267: FutureWarning:
Panel is deprecated and will be removed in a future version.
The recommended way to represent these types of 3-dimensional data are with a MultiIndex on a DataFrame, via the Panel.to_frame() method
Alternatively, you can use the xarray package http://xarray.pydata.org/en/stable/.
Pandas provides a `.to_xarray()` method to help automate this conversion.
exec(code_obj, self.user_global_ns, self.user_ns)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 0 to 3
Minor_axis axis: 0 to 2
#Create a Dictionary of series
d = 'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack',
'Lee','David','Gasper','Betina','Andres']),
'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),
'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])
#Create a DataFrame
df = pd.DataFrame(d)
df
Name
Age
Rating
0
Tom
25
4.23
1
James
26
3.24
2
Ricky
25
3.98
3
Vin
23
2.56
4
Steve
30
3.20
5
Smith
29
4.60
6
Jack
23
3.80
7
Lee
34
3.78
8
David
40
2.98
9
Gasper
30
4.80
10
Betina
51
4.10
11
Andres
46
3.65
df.sum() #默认是按行相加
Name TomJamesRickyVinSteveSmithJackLeeDavidGasperBe...
Age 382
Rating 44.92
dtype: object
for index, row in df.iterrows():
print(index)
print("********")
print(row)
print("########")
0
********
A 2016-01-01 00:00:00
x 0
y 0.529153
C Low
D 110.431
Name: 0, dtype: object
########
1
********
A 2016-01-02 00:00:00
x 1
y 0.713513
C Low
D 125.401
Name: 1, dtype: object
########
2
********
A 2016-01-03 00:00:00
x 2
y 0.751809
C Medium
D 112.447
Name: 2, dtype: object
########
3
********
A 2016-01-04 00:00:00
x 3
y 0.124047
C High
D 108.633
Name: 3, dtype: object
########
4
********
A 2016-01-05 00:00:00
x 4
y 0.472205
C Medium
D 102.751
Name: 4, dtype: object
########
5
********
A 2016-01-06 00:00:00
x 5
y 0.221076
C High
D 108.209
Name: 5, dtype: object
########
6
********
A 2016-01-07 00:00:00
x 6
y 0.231904
C High
D 104.982
Name: 6, dtype: object
########
7
********
A 2016-01-08 00:00:00
x 7
y 0.567697
C Medium
D 117.179
Name: 7, dtype: object
########
8
********
A 2016-01-09 00:00:00
x 8
y 0.384391
C Medium
D 94.1604
Name: 8, dtype: object
########
9
********
A 2016-01-10 00:00:00
x 9
y 0.109675
C Medium
D 108.561
Name: 9, dtype: object
########
10
********
A 2016-01-11 00:00:00
x 10
y 0.68148
C High
D 101.401
Name: 10, dtype: object
########
11
********
A 2016-01-12 00:00:00
x 11
y 0.918687
C Medium
D 102.421
Name: 11, dtype: object
########
12
********
A 2016-01-13 00:00:00
x 12
y 0.332227
C High
D 99.4647
Name: 12, dtype: object
########
13
********
A 2016-01-14 00:00:00
x 13
y 0.373779
C High
D 107.22
Name: 13, dtype: object
########
14
********
A 2016-01-15 00:00:00
x 14
y 0.412173
C Low
D 97.1846
Name: 14, dtype: object
########
15
********
A 2016-01-16 00:00:00
x 15
y 0.194842
C Medium
D 96.6712
Name: 15, dtype: object
########
16
********
A 2016-01-17 00:00:00
x 16
y 0.372288
C Low
D 105.27
Name: 16, dtype: object
########
17
********
A 2016-01-18 00:00:00
x 17
y 0.0688757
C Low
D 101.113
Name: 17, dtype: object
########
18
********
A 2016-01-19 00:00:00
x 18
y 0.391142
C High
D 102.241
Name: 18, dtype: object
########
19
********
A 2016-01-20 00:00:00
x 19
y 0.9426
C Low
D 92.4924
Name: 19, dtype: object
########
itertuples()
for row in df.itertuples():
print(row)
print("*********")
Help on method sort_index in module pandas.core.frame:
sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, by=None) method of pandas.core.frame.DataFrame instance
Sort object by labels (along an axis)
Parameters
----------
axis : index, columns to direct sorting
level : int or level name or list of ints or list of level names
if not None, sort on values in specified index level(s)
ascending : boolean, default True
Sort ascending vs. descending
inplace : bool, default False
if True, perform operation in-place
kind : 'quicksort', 'mergesort', 'heapsort', default 'quicksort'
Choice of sorting algorithm. See also ndarray.np.sort for more
information. `mergesort` is the only stable algorithm. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : 'first', 'last', default 'last'
`first` puts NaNs at the beginning, `last` puts NaNs at the end.
Not implemented for MultiIndex.
sort_remaining : bool, default True
if true and sorting by level and index is multilevel, sort by other
levels too (in order) after sorting by specified level
Returns
-------
sorted_obj : DataFrame
Help on method sort_values in module pandas.core.frame:
sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last') method of pandas.core.frame.DataFrame instance
Sort by the values along either axis
Parameters
----------
by : str or list of str
Name or list of names to sort by.
- if `axis` is 0 or `'index'` then `by` may contain index
levels and/or column labels
- if `axis` is 1 or `'columns'` then `by` may contain column
levels and/or index labels
.. versionchanged:: 0.23.0
Allow specifying index or column level names.
axis : 0 or 'index', 1 or 'columns', default 0
Axis to be sorted
ascending : bool or list of bool, default True
Sort ascending vs. descending. Specify list for multiple sort
orders. If this is a list of bools, must match the length of
the by.
inplace : bool, default False
if True, perform operation in-place
kind : 'quicksort', 'mergesort', 'heapsort', default 'quicksort'
Choice of sorting algorithm. See also ndarray.np.sort for more
information. `mergesort` is the only stable algorithm. For
DataFrames, this option is only applied when sorting on a single
column or label.
na_position : 'first', 'last', default 'last'
`first` puts NaNs at the beginning, `last` puts NaNs at the end
Returns
-------
sorted_obj : DataFrame
Examples
--------
>>> 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
Sort by col1
>>> 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
Sort by multiple columns
>>> df.sort_values(by=['col1', 'col2'])
col1 col2 col3
1 A 1 1
0 A 2 0
2 B 9 9
5 C 4 3
4 D 7 2
3 NaN 8 4
Sort Descending
>>> df.sort_values(by='col1', ascending=False)
col1 col2 col3
4 D 7 2
5 C 4 3
2 B 9 9
0 A 2 0
1 A 1 1
3 NaN 8 4
Putting NAs first
>>> df.sort_values(by='col1', ascending=False, na_position='first')
col1 col2 col3
3 NaN 8 4
4 D 7 2
5 C 4 3
2 B 9 9
0 A 2 0
1 A 1 1
a 2.539530
b -0.278140
c 1.291831
d -0.231592
e -2.047005
f -0.720743
g -0.995131
h 0.190029
Name: A, dtype: float64
df.loc[:, ['A', 'C']]
A
C
a
2.539530
-0.290170
b
-0.278140
1.575699
c
1.291831
0.038547
d
-0.231592
0.117562
e
-2.047005
-0.569768
f
-0.720743
0.321223
g
-0.995131
1.530757
h
0.190029
-0.068202
df.loc['a':'h']
A
B
C
D
a
2.539530
0.046380
-0.290170
-1.540302
b
-0.278140
1.420046
1.575699
0.533353
c
1.291831
2.595299
0.038547
-0.488134
d
-0.231592
-0.162497
0.117562
1.452291
e
-2.047005
-0.046110
-0.569768
1.328672
f
-0.720743
0.339251
0.321223
-0.310041
g
-0.995131
0.831769
1.530757
0.975214
h
0.190029
1.056606
-0.068202
-1.127776
df.loc[df.loc[:, 'A'] > 0, 'A']
b 0.530365
c 1.760542
e 0.866758
f 1.620520
Name: A, dtype: float64
iloc()
df.iloc[:4]
A
B
C
D
a
2.539530
0.046380
-0.290170
-1.540302
b
-0.278140
1.420046
1.575699
0.533353
c
1.291831
2.595299
0.038547
-0.488134
d
-0.231592
-0.162497
0.117562
1.452291
df.iloc[1:5, 2:4]
C
D
b
1.575699
0.533353
c
0.038547
-0.488134
d
0.117562
1.452291
e
-0.569768
1.328672
import collections
p = collections.defaultdict(int)
p['A'] += 1
p['B'] += 1
p
defaultdict(int, 'A': 1, 'B': 1)
df = pd.DataFrame('thing':['A', 'A', 'B', 'A', 'B', 'A', 'C', 'C', 'C'])
for row in df.loc[df.loc[:, 'thing']== 'D'].iterrows():
print(1)
x = set([1, 2, 3, 1])
x
1, 2, 3
df2 = df.copy()
df2
A
D
a
-0.235229
1.081632
b
0.530365
-1.958886
c
1.760542
0.299710
d
-0.241942
-0.513217
e
0.866758
-0.987964
f
1.620520
-1.012238
g
-0.236978
-0.195936
h
-0.046064
1.740141
df2.loc['a'][0] = 3
df3 = df['A']
df3
a -0.235229
b 0.530365
c 1.760542
d -0.241942
e 0.866758
f 1.620520
g -0.236978
h -0.046064
Name: A, dtype: float64
df3['a'] = 3
df3
a 3.000000
b 0.530365
c 1.760542
d -0.241942
e 0.866758
f 1.620520
g -0.236978
h -0.046064
Name: A, dtype: float64
df3 = df.iloc[:4]
df3
A
D
a
3.000000
1.081632
b
0.530365
-1.958886
c
1.760542
0.299710
d
-0.241942
-0.513217
df3.pop('A')
a 0.000000
b 0.530365
c 1.760542
d -0.241942
Name: A, dtype: float64
d = 1:1, 2:2
u = 3:3
d.update(u)
d
1: 1, 2: 2, 3: 3
Wroking with Text Data
s = pd.Series(['Tom', 'William Rick', 'John', 'Alber@t', np.nan, '1234','SteveSmith'])
s
0 Tom
1 William Rick
2 John
3 Alber@t
4 NaN
5 1234
6 SteveSmith
dtype: object
s.str.lower() s.str.upper()
list(s.str)
[0 T
1 W
2 J
3 A
4 NaN
5 1
6 S
dtype: object, 0 o
1 i
2 o
3 l
4 NaN
5 2
6 t
dtype: object, 0 m
1 l
2 h
3 b
4 NaN
5 3
6 e
dtype: object, 0 NaN
1 l
2 n
3 e
4 NaN
5 4
6 v
dtype: object, 0 NaN
1 i
2 NaN
3 r
4 NaN
5 NaN
6 e
dtype: object, 0 NaN
1 a
2 NaN
3 @
4 NaN
5 NaN
6 S
dtype: object, 0 NaN
1 m
2 NaN
3 t
4 NaN
5 NaN
6 m
dtype: object, 0 NaN
1
2 NaN
3 NaN
4 NaN
5 NaN
6 i
dtype: object, 0 NaN
1 R
2 NaN
3 NaN
4 NaN
5 NaN
6 t
dtype: object, 0 NaN
1 i
2 NaN
3 NaN
4 NaN
5 NaN
6 h
dtype: object, 0 NaN
1 c
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
dtype: object, 0 NaN
1 k
2 NaN
3 NaN
4 NaN
5 NaN
6 NaN
dtype: object]
s.str.lower() #所以这一步实际上就是把s.str的第一个部分全部改为小写?
0 tom
1 william rick
2 john
3 alber@t
4 NaN
5 1234
6 stevesmith
dtype: object
s.str.upper()
0 TOM
1 WILLIAM RICK
2 JOHN
3 ALBER@T
4 NaN
5 1234
6 STEVESMITH
dtype: object
Help on method cat in module pandas.core.strings:
cat(others=None, sep=None, na_rep=None, join=None) method of pandas.core.strings.StringMethods instance
Concatenate strings in the Series/Index with given separator.
If `others` is specified, this function concatenates the Series/Index
and elements of `others` element-wise.
If `others` is not passed, then all values in the Series/Index are
concatenated into a single string with a given `sep`.
Parameters
----------
others : Series, Index, DataFrame, np.ndarrary or list-like
Series, Index, DataFrame, np.ndarray (one- or two-dimensional) and
other list-likes of strings must have the same length as the
calling Series/Index, with the exception of indexed objects (i.e.
Series/Index/DataFrame) if `join` is not None.
If others is a list-like that contains a combination of Series,
np.ndarray (1-dim) or list-like, then all elements will be unpacked
and must satisfy the above criteria individually.
If others is None, the method returns the concatenation of all
strings in the calling Series/Index.
sep : string or None, default None
If None, concatenates without any separator.
na_rep : string or None, default None
Representation that is inserted for all missing values:
- If `na_rep` is None, and `others` is None, missing values in the
Series/Index are omitted from the result.
- If `na_rep` is None, and `others` is not None, a row containing a
missing value in any of the columns (before concatenation) will
have a missing value in the result.
join : 'left', 'right', 'outer', 'inner', default None
Determines the join-style between the calling Series/Index and any
Series/Index/DataFrame in `others` (objects without an index need
to match the length of the calling Series/Index). If None,
alignment is disabled, but this option will be removed in a future
version of pandas and replaced with a default of `'left'`. To
disable alignment, use `.values` on any Series/Index/DataFrame in
`others`.
.. versionadded:: 0.23.0
Returns
-------
concat : str or Series/Index of objects
If `others` is None, `str` is returned, otherwise a `Series/Index`
(same type as caller) of objects is returned.
See Also
--------
split : Split each string in the Series/Index
Examples
--------
When not passing `others`, all values are concatenated into a single
string:
>>> s = pd.Series(['a', 'b', np.nan, 'd'])
>>> s.str.cat(sep=' ')
'a b d'
By default, NA values in the Series are ignored. Using `na_rep`, they
can be given a representation:
>>> s.str.cat(sep=' ', na_rep='?')
'a b ? d'
If `others` is specified, corresponding values are concatenated with
the separator. Result will be a Series of strings.
>>> s.str.cat(['A', 'B', 'C', 'D'], sep=',')
0 a,A
1 b,B
2 NaN
3 d,D
dtype: object
Missing values will remain missing in the result, but can again be
represented using `na_rep`
>>> s.str.cat(['A', 'B', 'C', 'D'], sep=',', na_rep='-')
0 a,A
1 b,B
2 -,C
3 d,D
dtype: object
If `sep` is not specified, the values are concatenated without
separation.
>>> s.str.cat(['A', 'B', 'C', 'D'], na_rep='-')
0 aA
1 bB
2 -C
3 dD
dtype: object
Series with different indexes can be aligned before concatenation. The
`join`-keyword works as in other methods.
>>> t = pd.Series(['d', 'a', 'e', 'c'], index=[3, 0, 4, 2])
>>> s.str.cat(t, join=None, na_rep='-')
0 ad
1 ba
2 -e
3 dc
dtype: object
>>>
>>> s.str.cat(t, join='left', na_rep='-')
0 aa
1 b-
2 -c
3 dd
dtype: object
>>>
>>> s.str.cat(t, join='outer', na_rep='-')
0 aa
1 b-
2 -c
3 dd
4 -e
dtype: object
>>>
>>> s.str.cat(t, join='inner', na_rep='-')
0 aa
2 -c
3 dd
dtype: object
>>>
>>> s.str.cat(t, join='right', na_rep='-')
3 dd
0 aa
4 -e
2 -c
dtype: object
For more examples, see :ref:`here <text.concatenate>`.
s.str.get_dummies()
s.str.get_dummies()
William Rick
Alber@t
John
Tom
0
0
0
0
1
1
1
0
0
0
2
0
0
1
0
3
0
1
0
0
s = pd.Series(['Tom ', ' William Rick', 'Alber@t', 'John'])
s.str.get_dummies()
William Rick
Alber@t
John
Tom
0
0
0
0
1
1
1
0
0
0
2
0
1
0
0
3
0
0
1
0
所以是以DataFrame的形式来表示各个字符出现的顺序?
s.str.contains()
s.str.contains(' ')
0 True
1 True
2 False
3 False
dtype: bool
s.str.contains('o')
0 True
1 False
2 False
3 True
dtype: bool
s.str.replace()
s.str.replace('@', '$')
0 Tom
1 William Rick
2 Alber$t
3 John
dtype: object
s.str.repeat()
s = pd.Series(['Tom ', ' William Rick', 'Alber@t', 'John', np.nan])
s.str.repeat(3)
0 Tom Tom Tom
1 William Rick William Rick William Rick
2 Alber@tAlber@tAlber@t
3 JohnJohnJohn
dtype: object
s.str.repeat([1, 2, 3, 4])
0 Tom
1 William Rick William Rick
2 Alber@tAlber@tAlber@t
3 JohnJohnJohnJohn
dtype: object
display.max_rows : int
If max_rows is exceeded, switch to truncate view. Depending on
`large_repr`, objects are either centrally truncated or printed as
a summary view. 'None' value means unlimited.
In case python/IPython is running in a terminal and `large_repr`
equals 'truncate' this can be set to 0 and pandas will auto-detect
the height of the terminal and print a truncated object which fits
the screen height. The IPython notebook, IPython qtconsole, or
IDLE do not run in a terminal and hence it is not possible to do
correct auto-detection.
[default: 60] [currently: 60]
option_context()
with pd.option_context("display.max_rows", 10):
print(pd.get_option("display.max_rows"))
print(pd.get_option("display.max_rows"))
Help on method pct_change in module pandas.core.generic:
pct_change(periods=1, fill_method='pad', limit=None, freq=None, **kwargs) method of pandas.core.frame.DataFrame instance
Percentage change between the current and a prior element.
Computes the percentage change from the immediately previous row by
default. This is useful in comparing the percentage of change in a time
series of elements.
Parameters
----------
periods : int, default 1
Periods to shift for forming percent change.
fill_method : str, default 'pad'
How to handle NAs before computing percent changes.
limit : int, default None
The number of consecutive NAs to fill before stopping.
freq : DateOffset, timedelta, or offset alias string, optional
Increment to use from time series API (e.g. 'M' or BDay()).
**kwargs
Additional keyword arguments are passed into
`DataFrame.shift` or `Series.shift`.
Returns
-------
chg : Series or DataFrame
The same type as the calling object.
See Also
--------
Series.diff : Compute the difference of two elements in a Series.
DataFrame.diff : Compute the difference of two elements in a DataFrame.
Series.shift : Shift the index by some number of periods.
DataFrame.shift : Shift the index by some number of periods.
Examples
--------
**Series**
>>> s = pd.Series([90, 91, 85])
>>> s
0 90
1 91
2 85
dtype: int64
>>> s.pct_change()
0 NaN
1 0.011111
2 -0.065934
dtype: float64
>>> s.pct_change(periods=2)
0 NaN
1 NaN
2 -0.055556
dtype: float64
See the percentage change in a Series where filling NAs with last
valid observation forward to next valid.
>>> s = pd.Series([90, 91, None, 85])
>>> s
0 90.0
1 91.0
2 NaN
3 85.0
dtype: float64
>>> s.pct_change(fill_method='ffill')
0 NaN
1 0.011111
2 0.000000
3 -0.065934
dtype: float64
**DataFrame**
Percentage change in French franc, Deutsche Mark, and Italian lira from
1980-01-01 to 1980-03-01.
>>> df = pd.DataFrame(
... 'FR': [4.0405, 4.0963, 4.3149],
... 'GR': [1.7246, 1.7482, 1.8519],
... 'IT': [804.74, 810.01, 860.13],
... index=['1980-01-01', '1980-02-01', '1980-03-01'])
>>> df
FR GR IT
1980-01-01 4.0405 1.7246 804.74
1980-02-01 4.0963 1.7482 810.01
1980-03-01 4.3149 1.8519 860.13
>>> df.pct_change()
FR GR IT
1980-01-01 NaN NaN NaN
1980-02-01 0.013810 0.013684 0.006549
1980-03-01 0.053365 0.059318 0.061876
Percentage of change in GOOG and APPL stock volume. Shows computing
the percentage change between columns.
>>> df = pd.DataFrame(
... '2016': [1769950, 30586265],
... '2015': [1500923, 40912316],
... '2014': [1371819, 41403351],
... index=['GOOG', 'APPL'])
>>> df
2016 2015 2014
GOOG 1769950 1500923 1371819
APPL 30586265 40912316 41403351
>>> df.pct_change(axis='columns')
2016 2015 2014
GOOG NaN -0.151997 -0.086016
APPL NaN 0.337604 0.012002
s.pct_change(2)
0 NaN
1 NaN
2 2.000000
3 1.000000
4 0.666667
5 0.000000
dtype: float64
Help on method fillna in module pandas.core.frame:
fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs) method of pandas.core.frame.DataFrame instance
Fill NA/NaN values using the specified method
Parameters
----------
value : scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a
dict/Series/DataFrame of values specifying which value to use for
each index (for a Series) or column (for a DataFrame). (values not
in the dict/Series/DataFrame will not be filled). This value cannot
be a list.
method : 'backfill', 'bfill', 'pad', 'ffill', None, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
backfill / bfill: use NEXT valid observation to fill gap
axis : 0 or 'index', 1 or 'columns'
inplace : boolean, default False
If True, fill in place. Note: this will modify any
other views on this object, (e.g. a no-copy slice for a column in a
DataFrame).
limit : int, default None
If method is specified, this is the maximum number of consecutive
NaN values to forward/backward fill. In other words, if there is
a gap with more than this number of consecutive NaNs, it will only
be partially filled. If method is not specified, this is the
maximum number of entries along the entire axis where NaNs will be
filled. Must be greater than 0 if not None.
downcast : dict, default is None
a dict of item->dtype of what to downcast if possible,
or the string 'infer' which will try to downcast to an appropriate
equal type (e.g. float64 to int64 if possible)
See Also
--------
interpolate : Fill NaN values using interpolation.
reindex, asfreq
Returns
-------
filled : DataFrame
Examples
--------
>>> df = pd.DataFrame([[np.nan, 2, np.nan, 0],
... [3, 4, np.nan, 1],
... [np.nan, np.nan, np.nan, 5],
... [np.nan, 3, np.nan, 4]],
... columns=list('ABCD'))
>>> df
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 NaN NaN NaN 5
3 NaN 3.0 NaN 4
Replace all NaN elements with 0s.
>>> df.fillna(0)
A B C D
0 0.0 2.0 0.0 0
1 3.0 4.0 0.0 1
2 0.0 0.0 0.0 5
3 0.0 3.0 0.0 4
We can also propagate non-null values forward or backward.
>>> df.fillna(method='ffill')
A B C D
0 NaN 2.0 NaN 0
1 3.0 4.0 NaN 1
2 3.0 4.0 NaN 5
3 3.0 3.0 NaN 4
Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,
2, and 3 respectively.
>>> values = 'A': 0, 'B': 1, 'C': 2, 'D': 3
>>> df.fillna(value=values)
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 2.0 1
2 0.0 1.0 2.0 5
3 0.0 3.0 2.0 4
Only replace the first NaN element.
>>> df.fillna(value=values, limit=1)
A B C D
0 0.0 2.0 2.0 0
1 3.0 4.0 NaN 1
2 NaN 1.0 NaN 5
3 NaN 3.0 NaN 4
Help on method replace in module pandas.core.frame:
replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method='pad') method of pandas.core.frame.DataFrame instance
Replace values given in `to_replace` with `value`.
Values of the DataFrame are replaced with other values dynamically.
This differs from updating with ``.loc`` or ``.iloc``, which require
you to specify a location to update with some value.
Parameters
----------
to_replace : str, regex, list, dict, Series, int, float, or None
How to find the values that will be replaced.
* numeric, str or regex:
- numeric: numeric values equal to `to_replace` will be
replaced with `value`
- str: string exactly matching `to_replace` will be replaced
with `value`
- regex: regexs matching `to_replace` will be replaced with
`value`
* list of str, regex, or numeric:
- First, if `to_replace` and `value` are both lists, they
**must** be the same length.
- Second, if ``regex=True`` then all of the strings in **both**
lists will be interpreted as regexs otherwise they will match
directly. This doesn't matter much for `value` since there
are only a few possible substitution regexes you can use.
- str, regex and numeric rules apply as above.
* dict:
- Dicts can be used to specify different replacement values
for different existing values. For example,
``'a': 'b', 'y': 'z'`` replaces the value 'a' with 'b' and
'y' with 'z'. To use a dict in this way the `value`
parameter should be `None`.
- For a DataFrame a dict can specify that different values
should be replaced in different columns. For example,
``'a': 1, 'b': 'z'`` looks for the value 1 in column 'a'
and the value 'z' in column 'b' and replaces these values
with whatever is specified in `value`. The `value` parameter
should not be ``None`` in this case. You can treat this as a
special case of passing two lists except that you are
specifying the column to search in.
- For a DataFrame nested dictionaries, e.g.,
``'a': 'b': np.nan``, are read as follows: look in column
'a' for the value 'b' and replace it with NaN. The `value`
parameter should be ``None`` to use a nested dict in this
way. You can nest regular expressions as well. Note that
column names (the top-level dictionary keys in a nested
dictionary) **cannot** be regular expressions.
* None:
- This means that the `regex` argument must be a string,
compiled regular expression, or list, dict, ndarray or
Series of such elements. If `value` is also ``None`` then
this **must** be a nested dictionary or Series.
See the examples section for examples of each of these.
value : scalar, dict, list, str, regex, default None
Value to replace any values matching `to_replace` with.
For a DataFrame a dict of values can be used to specify which
value to use for each column (columns not in the dict will not be
filled). Regular expressions, strings and lists or dicts of such
objects are also allowed.
inplace : boolean, default False
If True, in place. Note: this will modify any
other views on this object (e.g. a column from a DataFrame).
Returns the caller if this is True.
limit : int, default None
Maximum size gap to forward or backward fill.
regex : bool or same types as `to_replace`, default False
Whether to interpret `to_replace` and/or `value` as regular
expressions. If this is ``True`` then `to_replace` *must* be a
string. Alternatively, this could be a regular expression or a
list, dict, or array of regular expressions in which case
`to_replace` must be ``None``.
method : 'pad', 'ffill', 'bfill', `None`
The method to use when for replacement, when `to_replace` is a
scalar, list or tuple and `value` is ``None``.
.. versionchanged:: 0.23.0
Added to DataFrame.
See Also
--------
DataFrame.fillna : Fill NA values
DataFrame.where : Replace values based on boolean condition
Series.str.replace : Simple string replacement.
Returns
-------
DataFrame
Object after replacement.
Raises
------
AssertionError
* If `regex` is not a ``bool`` and `to_replace` is not
``None``.
TypeError
* If `to_replace` is a ``dict`` and `value` is not a ``list``,
``dict``, ``ndarray``, or ``Series``
* If `to_replace` is ``None`` and `regex` is not compilable
into a regular expression or is a list, dict, ndarray, or
Series.
* When replacing multiple ``bool`` or ``datetime64`` objects and
the arguments to `to_replace` does not match the type of the
value being replaced
ValueError
* If a ``list`` or an ``ndarray`` is passed to `to_replace` and
`value` but they are not the same length.
Notes
-----
* Regex substitution is performed under the hood with ``re.sub``. The
rules for substitution for ``re.sub`` are the same.
* Regular expressions will only substitute on strings, meaning you
cannot provide, for example, a regular expression matching floating
point numbers and expect the columns in your frame that have a
numeric dtype to be matched. However, if those floating point
numbers *are* strings, then you can do this.
* This method has *a lot* of options. You are encouraged to experiment
and play with this method to gain intuition about how it works.
* When dict is used as the `to_replace` value, it is like
key(s) in the dict are the to_replace part and
value(s) in the dict are the value parameter.
Examples
--------
**Scalar `to_replace` and `value`**
>>> s = pd.Series([0, 1, 2, 3, 4])
>>> s.replace(0, 5)
0 5
1 1
2 2
3 3
4 4
dtype: int64
>>> df = pd.DataFrame('A': [0, 1, 2, 3, 4],
... 'B': [5, 6, 7, 8, 9],
... 'C': ['a', 'b', 'c', 'd', 'e'])
>>> df.replace(0, 5)
A B C
0 5 5 a
1 1 6 b
2 2 7 c
3 3 8 d
4 4 9 e
**List-like `to_replace`**
>>> df.replace([0, 1, 2, 3], 4)
A B C
0 4 5 a
1 4 6 b
2 4 7 c
3 4 8 d
4 4 9 e
>>> df.replace([0, 1, 2, 3], [4, 3, 2, 1])
A B C
0 4 5 a
1 3 6 b
2 2 7 c
3 1 8 d
4 4 9 e
>>> s.replace([1, 2], method='bfill')
0 0
1 3
2 3
3 3
4 4
dtype: int64
**dict-like `to_replace`**
>>> df.replace(0: 10, 1: 100)
A B C
0 10 5 a
1 100 6 b
2 2 7 c
3 3 8 d
4 4 9 e
>>> df.replace('A': 0, 'B': 5, 100)
A B C
0 100 100 a
1 1 6 b
2 2 7 c
3 3 8 d
4 4 9 e
>>> df.replace('A': 0: 100, 4: 400)
A B C
0 100 5 a
1 1 6 b
2 2 7 c
3 3 8 d
4 400 9 e
**Regular expression `to_replace`**
>>> df = pd.DataFrame('A': ['bat', 'foo', 'bait'],
... 'B': ['abc', 'bar', 'xyz'])
>>> df.replace(to_replace=r'^ba.$', value='new', regex=True)
A B
0 new abc
1 foo new
2 bait xyz
>>> df.replace('A': r'^ba.$', 'A': 'new', regex=True)
A B
0 new abc
1 foo bar
2 bait xyz
>>> df.replace(regex=r'^ba.$', value='new')
A B
0 new abc
1 foo new
2 bait xyz
>>> df.replace(regex=r'^ba.$':'new', 'foo':'xyz')
A B
0 new abc
1 xyz new
2 bait xyz
>>> df.replace(regex=[r'^ba.$', 'foo'], value='new')
A B
0 new abc
1 new new
2 bait xyz
Note that when replacing multiple ``bool`` or ``datetime64`` objects,
the data types in the `to_replace` parameter must match the data
type of the value being replaced:
>>> df = pd.DataFrame('A': [True, False, True],
... 'B': [False, True, False])
>>> df.replace('a string': 'new value', True: False) # raises
Traceback (most recent call last):
...
TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'
This raises a ``TypeError`` because one of the ``dict`` keys is not of
the correct type for replacement.
Compare the behavior of ``s.replace('a': None)`` and
``s.replace('a', None)`` to understand the pecularities
of the `to_replace` parameter:
>>> s = pd.Series([10, 'a', 'a', 'b', 'a'])
When one uses a dict as the `to_replace` value, it is like the
value(s) in the dict are equal to the `value` parameter.
``s.replace('a': None)`` is equivalent to
``s.replace(to_replace='a': None, value=None, method=None)``:
>>> s.replace('a': None)
0 10
1 None
2 None
3 b
4 None
dtype: object
When ``value=None`` and `to_replace` is a scalar, list or
tuple, `replace` uses the method parameter (default 'pad') to do the
replacement. So this is why the 'a' values are being replaced by 10
in rows 1 and 2 and 'b' in row 4 in this case.
The command ``s.replace('a', None)`` is actually equivalent to
``s.replace(to_replace='a', value=None, method='pad')``:
>>> s.replace('a', None)
0 10
1 10
2 10
3 b
4 b
dtype: object