清理/填充缺失数据

pandas objects are equipped with various data manipulation methods for dealing with missing data.

Filling missing values: fillna

fillna() can “fill in” NA values with non-NA data in a couple of ways, which we illustrate:

Replace NA with a scalar value

  1. In [41]: df2
  2. Out[41]:
  3. one two three four five timestamp
  4. a NaN 0.501113 -0.355322 bar False NaT
  5. c NaN 0.580967 0.983801 bar False NaT
  6. e 0.057802 0.761948 -0.712964 bar True 2012-01-01
  7. f -0.443160 -0.974602 1.047704 bar False 2012-01-01
  8. h NaN -1.053898 -0.019369 bar False NaT
  9. In [42]: df2.fillna(0)
  10. Out[42]:
  11. one two three four five timestamp
  12. a 0.000000 0.501113 -0.355322 bar False 0
  13. c 0.000000 0.580967 0.983801 bar False 0
  14. e 0.057802 0.761948 -0.712964 bar True 2012-01-01 00:00:00
  15. f -0.443160 -0.974602 1.047704 bar False 2012-01-01 00:00:00
  16. h 0.000000 -1.053898 -0.019369 bar False 0
  17. In [43]: df2['one'].fillna('missing')
  18. Out[43]:
  19. a missing
  20. c missing
  21. e 0.057802
  22. f -0.44316
  23. h missing
  24. Name: one, dtype: object

Fill gaps forward or backward

Using the same filling arguments as reindexing, we can propagate non-NA values forward or backward:

  1. In [44]: df
  2. Out[44]:
  3. one two three
  4. a NaN 0.501113 -0.355322
  5. c NaN 0.580967 0.983801
  6. e 0.057802 0.761948 -0.712964
  7. f -0.443160 -0.974602 1.047704
  8. h NaN -1.053898 -0.019369
  9. In [45]: df.fillna(method='pad')
  10. Out[45]:
  11. one two three
  12. a NaN 0.501113 -0.355322
  13. c NaN 0.580967 0.983801
  14. e 0.057802 0.761948 -0.712964
  15. f -0.443160 -0.974602 1.047704
  16. h -0.443160 -1.053898 -0.019369

Limit the amount of filling

If we only want consecutive gaps filled up to a certain number of data points, we can use the limit keyword:

  1. In [46]: df
  2. Out[46]:
  3. one two three
  4. a NaN 0.501113 -0.355322
  5. c NaN 0.580967 0.983801
  6. e NaN NaN NaN
  7. f NaN NaN NaN
  8. h NaN -1.053898 -0.019369
  9. In [47]: df.fillna(method='pad', limit=1)
  10. Out[47]:
  11. one two three
  12. a NaN 0.501113 -0.355322
  13. c NaN 0.580967 0.983801
  14. e NaN 0.580967 0.983801
  15. f NaN NaN NaN
  16. h NaN -1.053898 -0.019369

To remind you, these are the available filling methods:

MethodAction
pad / ffillFill values forward
bfill / backfillFill values backward

With time series data, using pad/ffill is extremely common so that the “last known value” is available at every time point.

ffill() is equivalent to fillna(method='ffill') and bfill() is equivalent to fillna(method='bfill')

Filling with a PandasObject

You can also fillna using a dict or Series that is alignable. The labels of the dict or index of the Series must match the columns of the frame you wish to fill. The use case of this is to fill a DataFrame with the mean of that column.

  1. In [48]: dff = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'))
  2. In [49]: dff.iloc[3:5,0] = np.nan
  3. In [50]: dff.iloc[4:6,1] = np.nan
  4. In [51]: dff.iloc[5:8,2] = np.nan
  5. In [52]: dff
  6. Out[52]:
  7. A B C
  8. 0 0.758887 2.340598 0.219039
  9. 1 -1.235583 0.031785 0.701683
  10. 2 -1.557016 -0.636986 -1.238610
  11. 3 NaN -1.002278 0.654052
  12. 4 NaN NaN 1.053999
  13. 5 0.651981 NaN NaN
  14. 6 0.109001 -0.533294 NaN
  15. 7 -1.037831 -1.150016 NaN
  16. 8 -0.687693 1.921056 -0.121113
  17. 9 -0.258742 -0.706329 0.402547
  18. In [53]: dff.fillna(dff.mean())
  19. Out[53]:
  20. A B C
  21. 0 0.758887 2.340598 0.219039
  22. 1 -1.235583 0.031785 0.701683
  23. 2 -1.557016 -0.636986 -1.238610
  24. 3 -0.407125 -1.002278 0.654052
  25. 4 -0.407125 0.033067 1.053999
  26. 5 0.651981 0.033067 0.238800
  27. 6 0.109001 -0.533294 0.238800
  28. 7 -1.037831 -1.150016 0.238800
  29. 8 -0.687693 1.921056 -0.121113
  30. 9 -0.258742 -0.706329 0.402547
  31. In [54]: dff.fillna(dff.mean()['B':'C'])
  32. Out[54]:
  33. A B C
  34. 0 0.758887 2.340598 0.219039
  35. 1 -1.235583 0.031785 0.701683
  36. 2 -1.557016 -0.636986 -1.238610
  37. 3 NaN -1.002278 0.654052
  38. 4 NaN 0.033067 1.053999
  39. 5 0.651981 0.033067 0.238800
  40. 6 0.109001 -0.533294 0.238800
  41. 7 -1.037831 -1.150016 0.238800
  42. 8 -0.687693 1.921056 -0.121113
  43. 9 -0.258742 -0.706329 0.402547

Same result as above, but is aligning the ‘fill’ value which is a Series in this case.

  1. In [55]: dff.where(pd.notna(dff), dff.mean(), axis='columns')
  2. Out[55]:
  3. A B C
  4. 0 0.758887 2.340598 0.219039
  5. 1 -1.235583 0.031785 0.701683
  6. 2 -1.557016 -0.636986 -1.238610
  7. 3 -0.407125 -1.002278 0.654052
  8. 4 -0.407125 0.033067 1.053999
  9. 5 0.651981 0.033067 0.238800
  10. 6 0.109001 -0.533294 0.238800
  11. 7 -1.037831 -1.150016 0.238800
  12. 8 -0.687693 1.921056 -0.121113
  13. 9 -0.258742 -0.706329 0.402547

Dropping axis labels with missing data: dropna

You may wish to simply exclude labels from a data set which refer to missing data. To do this, use dropna():

  1. In [56]: df
  2. Out[56]:
  3. one two three
  4. a NaN 0.501113 -0.355322
  5. c NaN 0.580967 0.983801
  6. e NaN 0.000000 0.000000
  7. f NaN 0.000000 0.000000
  8. h NaN -1.053898 -0.019369
  9. In [57]: df.dropna(axis=0)
  10. Out[57]:
  11. Empty DataFrame
  12. Columns: [one, two, three]
  13. Index: []
  14. In [58]: df.dropna(axis=1)
  15. Out[58]:
  16. two three
  17. a 0.501113 -0.355322
  18. c 0.580967 0.983801
  19. e 0.000000 0.000000
  20. f 0.000000 0.000000
  21. h -1.053898 -0.019369
  22. In [59]: df['one'].dropna()
  23. Out[59]: Series([], Name: one, dtype: float64)

An equivalent dropna() is available for Series. DataFrame.dropna has considerably more options than Series.dropna, which can be examined in the API.

Interpolation

New in version 0.21.0: The limit_area keyword argument was added.

Both Series and DataFrame objects have interpolate() that, by default, performs linear interpolation at missing datapoints.

  1. In [60]: ts
  2. Out[60]:
  3. 2000-01-31 0.469112
  4. 2000-02-29 NaN
  5. 2000-03-31 NaN
  6. 2000-04-28 NaN
  7. 2000-05-31 NaN
  8. 2000-06-30 NaN
  9. 2000-07-31 NaN
  10. ...
  11. 2007-10-31 -3.305259
  12. 2007-11-30 -5.485119
  13. 2007-12-31 -6.854968
  14. 2008-01-31 -7.809176
  15. 2008-02-29 -6.346480
  16. 2008-03-31 -8.089641
  17. 2008-04-30 -8.916232
  18. Freq: BM, Length: 100, dtype: float64
  19. In [61]: ts.count()
  20. Out[61]: 61
  21. In [62]: ts.interpolate().count()
  22. Out[62]: 100
  23. In [63]: ts.interpolate().plot()
  24. Out[63]: <matplotlib.axes._subplots.AxesSubplot at 0x7f20cf59ca58>

_images/series_interpolate.png

Index aware interpolation is available via the method keyword:

  1. In [64]: ts2
  2. Out[64]:
  3. 2000-01-31 0.469112
  4. 2000-02-29 NaN
  5. 2002-07-31 -5.689738
  6. 2005-01-31 NaN
  7. 2008-04-30 -8.916232
  8. dtype: float64
  9. In [65]: ts2.interpolate()
  10. Out[65]:
  11. 2000-01-31 0.469112
  12. 2000-02-29 -2.610313
  13. 2002-07-31 -5.689738
  14. 2005-01-31 -7.302985
  15. 2008-04-30 -8.916232
  16. dtype: float64
  17. In [66]: ts2.interpolate(method='time')
  18. Out[66]:
  19. 2000-01-31 0.469112
  20. 2000-02-29 0.273272
  21. 2002-07-31 -5.689738
  22. 2005-01-31 -7.095568
  23. 2008-04-30 -8.916232
  24. dtype: float64

For a floating-point index, use method='values':

  1. In [67]: ser
  2. Out[67]:
  3. 0.0 0.0
  4. 1.0 NaN
  5. 10.0 10.0
  6. dtype: float64
  7. In [68]: ser.interpolate()
  8. Out[68]:
  9. 0.0 0.0
  10. 1.0 5.0
  11. 10.0 10.0
  12. dtype: float64
  13. In [69]: ser.interpolate(method='values')
  14. Out[69]:
  15. 0.0 0.0
  16. 1.0 1.0
  17. 10.0 10.0
  18. dtype: float64

You can also interpolate with a DataFrame:

  1. In [70]: df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8],
  2. ....: 'B': [.25, np.nan, np.nan, 4, 12.2, 14.4]})
  3. ....:
  4. In [71]: df
  5. Out[71]:
  6. A B
  7. 0 1.0 0.25
  8. 1 2.1 NaN
  9. 2 NaN NaN
  10. 3 4.7 4.00
  11. 4 5.6 12.20
  12. 5 6.8 14.40
  13. In [72]: df.interpolate()
  14. Out[72]:
  15. A B
  16. 0 1.0 0.25
  17. 1 2.1 1.50
  18. 2 3.4 2.75
  19. 3 4.7 4.00
  20. 4 5.6 12.20
  21. 5 6.8 14.40

The method argument gives access to fancier interpolation methods. If you have scipy installed, you can pass the name of a 1-d interpolation routine to method. You’ll want to consult the full scipy interpolation documentation and reference guide for details. The appropriate interpolation method will depend on the type of data you are working with.

  • If you are dealing with a time series that is growing at an increasing rate, method='quadratic' may be appropriate.
  • If you have values approximating a cumulative distribution function, then method='pchip' should work well.
  • To fill missing values with goal of smooth plotting, consider method='akima'.

警告

These methods require scipy.

  1. In [73]: df.interpolate(method='barycentric')
  2. Out[73]:
  3. A B
  4. 0 1.00 0.250
  5. 1 2.10 -7.660
  6. 2 3.53 -4.515
  7. 3 4.70 4.000
  8. 4 5.60 12.200
  9. 5 6.80 14.400
  10. In [74]: df.interpolate(method='pchip')
  11. Out[74]:
  12. A B
  13. 0 1.00000 0.250000
  14. 1 2.10000 0.672808
  15. 2 3.43454 1.928950
  16. 3 4.70000 4.000000
  17. 4 5.60000 12.200000
  18. 5 6.80000 14.400000
  19. In [75]: df.interpolate(method='akima')
  20. Out[75]:
  21. A B
  22. 0 1.000000 0.250000
  23. 1 2.100000 -0.873316
  24. 2 3.406667 0.320034
  25. 3 4.700000 4.000000
  26. 4 5.600000 12.200000
  27. 5 6.800000 14.400000

When interpolating via a polynomial or spline approximation, you must also specify the degree or order of the approximation:

  1. In [76]: df.interpolate(method='spline', order=2)
  2. Out[76]:
  3. A B
  4. 0 1.000000 0.250000
  5. 1 2.100000 -0.428598
  6. 2 3.404545 1.206900
  7. 3 4.700000 4.000000
  8. 4 5.600000 12.200000
  9. 5 6.800000 14.400000
  10. In [77]: df.interpolate(method='polynomial', order=2)
  11. Out[77]:
  12. A B
  13. 0 1.000000 0.250000
  14. 1 2.100000 -2.703846
  15. 2 3.451351 -1.453846
  16. 3 4.700000 4.000000
  17. 4 5.600000 12.200000
  18. 5 6.800000 14.400000

Compare several methods:

  1. In [78]: np.random.seed(2)
  2. In [79]: ser = pd.Series(np.arange(1, 10.1, .25)**2 + np.random.randn(37))
  3. In [80]: bad = np.array([4, 13, 14, 15, 16, 17, 18, 20, 29])
  4. In [81]: ser[bad] = np.nan
  5. In [82]: methods = ['linear', 'quadratic', 'cubic']
  6. In [83]: df = pd.DataFrame({m: ser.interpolate(method=m) for m in methods})
  7. In [84]: df.plot()
  8. Out[84]: <matplotlib.axes._subplots.AxesSubplot at 0x7f20cf573fd0>

_images/compare_interpolations.png

Another use case is interpolation at new values. Suppose you have 100 observations from some distribution. And let’s suppose that you’re particularly interested in what’s happening around the middle. You can mix pandas’ reindex and interpolate methods to interpolate at the new values.

  1. In [85]: ser = pd.Series(np.sort(np.random.uniform(size=100)))
  2. # interpolate at new_index
  3. In [86]: new_index = ser.index | pd.Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])
  4. In [87]: interp_s = ser.reindex(new_index).interpolate(method='pchip')
  5. In [88]: interp_s[49:51]
  6. Out[88]:
  7. 49.00 0.471410
  8. 49.25 0.476841
  9. 49.50 0.481780
  10. 49.75 0.485998
  11. 50.00 0.489266
  12. 50.25 0.491814
  13. 50.50 0.493995
  14. 50.75 0.495763
  15. 51.00 0.497074
  16. dtype: float64

Interpolation Limits

Like other pandas fill methods, interpolate() accepts a limit keyword argument. Use this argument to limit the number of consecutive NaN values filled since the last valid observation:

  1. In [89]: ser = pd.Series([np.nan, np.nan, 5, np.nan, np.nan, np.nan, 13, np.nan, np.nan])
  2. # fill all consecutive values in a forward direction
  3. In [90]: ser.interpolate()
  4. Out[90]:
  5. 0 NaN
  6. 1 NaN
  7. 2 5.0
  8. 3 7.0
  9. 4 9.0
  10. 5 11.0
  11. 6 13.0
  12. 7 13.0
  13. 8 13.0
  14. dtype: float64
  15. # fill one consecutive value in a forward direction
  16. In [91]: ser.interpolate(limit=1)
  17. Out[91]:
  18. 0 NaN
  19. 1 NaN
  20. 2 5.0
  21. 3 7.0
  22. 4 NaN
  23. 5 NaN
  24. 6 13.0
  25. 7 13.0
  26. 8 NaN
  27. dtype: float64

By default, NaN values are filled in a forward direction. Use limit_direction parameter to fill backward or from both directions.

  1. # fill one consecutive value backwards
  2. In [92]: ser.interpolate(limit=1, limit_direction='backward')
  3. Out[92]:
  4. 0 NaN
  5. 1 5.0
  6. 2 5.0
  7. 3 NaN
  8. 4 NaN
  9. 5 11.0
  10. 6 13.0
  11. 7 NaN
  12. 8 NaN
  13. dtype: float64
  14. # fill one consecutive value in both directions
  15. In [93]: ser.interpolate(limit=1, limit_direction='both')
  16. Out[93]:
  17. 0 NaN
  18. 1 5.0
  19. 2 5.0
  20. 3 7.0
  21. 4 NaN
  22. 5 11.0
  23. 6 13.0
  24. 7 13.0
  25. 8 NaN
  26. dtype: float64
  27. # fill all consecutive values in both directions
  28. In [94]: ser.interpolate(limit_direction='both')
  29. Out[94]:
  30. 0 5.0
  31. 1 5.0
  32. 2 5.0
  33. 3 7.0
  34. 4 9.0
  35. 5 11.0
  36. 6 13.0
  37. 7 13.0
  38. 8 13.0
  39. dtype: float64

By default, NaN values are filled whether they are inside (surrounded by) existing valid values, or outside existing valid values. Introduced in v0.23 the limit_area parameter restricts filling to either inside or outside values.

  1. # fill one consecutive inside value in both directions
  2. In [95]: ser.interpolate(limit_direction='both', limit_area='inside', limit=1)
  3. Out[95]:
  4. 0 NaN
  5. 1 NaN
  6. 2 5.0
  7. 3 7.0
  8. 4 NaN
  9. 5 11.0
  10. 6 13.0
  11. 7 NaN
  12. 8 NaN
  13. dtype: float64
  14. # fill all consecutive outside values backward
  15. In [96]: ser.interpolate(limit_direction='backward', limit_area='outside')
  16. Out[96]:
  17. 0 5.0
  18. 1 5.0
  19. 2 5.0
  20. 3 NaN
  21. 4 NaN
  22. 5 NaN
  23. 6 13.0
  24. 7 NaN
  25. 8 NaN
  26. dtype: float64
  27. # fill all consecutive outside values in both directions
  28. In [97]: ser.interpolate(limit_direction='both', limit_area='outside')
  29. Out[97]:
  30. 0 5.0
  31. 1 5.0
  32. 2 5.0
  33. 3 NaN
  34. 4 NaN
  35. 5 NaN
  36. 6 13.0
  37. 7 13.0
  38. 8 13.0
  39. dtype: float64

Replacing Generic Values

Often times we want to replace arbitrary values with other values.

replace() in Series and replace() in DataFrame provides an efficient yet flexible way to perform such replacements.

For a Series, you can replace a single value or a list of values by another value:

  1. In [98]: ser = pd.Series([0., 1., 2., 3., 4.])
  2. In [99]: ser.replace(0, 5)
  3. Out[99]:
  4. 0 5.0
  5. 1 1.0
  6. 2 2.0
  7. 3 3.0
  8. 4 4.0
  9. dtype: float64

You can replace a list of values by a list of other values:

  1. In [100]: ser.replace([0, 1, 2, 3, 4], [4, 3, 2, 1, 0])
  2. Out[100]:
  3. 0 4.0
  4. 1 3.0
  5. 2 2.0
  6. 3 1.0
  7. 4 0.0
  8. dtype: float64

You can also specify a mapping dict:

  1. In [101]: ser.replace({0: 10, 1: 100})
  2. Out[101]:
  3. 0 10.0
  4. 1 100.0
  5. 2 2.0
  6. 3 3.0
  7. 4 4.0
  8. dtype: float64

For a DataFrame, you can specify individual values by column:

  1. In [102]: df = pd.DataFrame({'a': [0, 1, 2, 3, 4], 'b': [5, 6, 7, 8, 9]})
  2. In [103]: df.replace({'a': 0, 'b': 5}, 100)
  3. Out[103]:
  4. a b
  5. 0 100 100
  6. 1 1 6
  7. 2 2 7
  8. 3 3 8
  9. 4 4 9

Instead of replacing with specified values, you can treat all given values as missing and interpolate over them:

  1. In [104]: ser.replace([1, 2, 3], method='pad')
  2. Out[104]:
  3. 0 0.0
  4. 1 0.0
  5. 2 0.0
  6. 3 0.0
  7. 4 4.0
  8. dtype: float64

String/Regular Expression Replacement

Note: Python strings prefixed with the r character such as r’hello world’ are so-called “raw” strings. They have different semantics regarding backslashes than strings without this prefix. Backslashes in raw strings will be interpreted as an escaped backslash, e.g., r’’ == ‘\‘. You should read about them if this is unclear.

Replace the ‘.’ with NaN (str -> str):

  1. In [105]: d = {'a': list(range(4)), 'b': list('ab..'), 'c': ['a', 'b', np.nan, 'd']}
  2. In [106]: df = pd.DataFrame(d)
  3. In [107]: df.replace('.', np.nan)
  4. Out[107]:
  5. a b c
  6. 0 0 a a
  7. 1 1 b b
  8. 2 2 NaN NaN
  9. 3 3 NaN d

Now do it with a regular expression that removes surrounding whitespace (regex -> regex):

  1. In [108]: df.replace(r'\s*\.\s*', np.nan, regex=True)
  2. Out[108]:
  3. a b c
  4. 0 0 a a
  5. 1 1 b b
  6. 2 2 NaN NaN
  7. 3 3 NaN d

Replace a few different values (list -> list):

  1. In [109]: df.replace(['a', '.'], ['b', np.nan])
  2. Out[109]:
  3. a b c
  4. 0 0 b b
  5. 1 1 b b
  6. 2 2 NaN NaN
  7. 3 3 NaN d

list of regex -> list of regex:

  1. In [110]: df.replace([r'\.', r'(a)'], ['dot', '\1stuff'], regex=True)
  2. Out[110]:
  3. a b c
  4. 0 0 stuff stuff
  5. 1 1 b b
  6. 2 2 dot NaN
  7. 3 3 dot d

Only search in column 'b' (dict -> dict):

  1. In [111]: df.replace({'b': '.'}, {'b': np.nan})
  2. Out[111]:
  3. a b c
  4. 0 0 a a
  5. 1 1 b b
  6. 2 2 NaN NaN
  7. 3 3 NaN d

Same as the previous example, but use a regular expression for searching instead (dict of regex -> dict):

  1. In [112]: df.replace({'b': r'\s*\.\s*'}, {'b': np.nan}, regex=True)
  2. Out[112]:
  3. a b c
  4. 0 0 a a
  5. 1 1 b b
  6. 2 2 NaN NaN
  7. 3 3 NaN d

You can pass nested dictionaries of regular expressions that use regex=True:

  1. In [113]: df.replace({'b': {'b': r''}}, regex=True)
  2. Out[113]:
  3. a b c
  4. 0 0 a a
  5. 1 1 b
  6. 2 2 . NaN
  7. 3 3 . d

Alternatively, you can pass the nested dictionary like so:

  1. In [114]: df.replace(regex={'b': {r'\s*\.\s*': np.nan}})
  2. Out[114]:
  3. a b c
  4. 0 0 a a
  5. 1 1 b b
  6. 2 2 NaN NaN
  7. 3 3 NaN d

You can also use the group of a regular expression match when replacing (dict of regex -> dict of regex), this works for lists as well.

  1. In [115]: df.replace({'b': r'\s*(\.)\s*'}, {'b': r'\1ty'}, regex=True)
  2. Out[115]:
  3. a b c
  4. 0 0 a a
  5. 1 1 b b
  6. 2 2 .ty NaN
  7. 3 3 .ty d

You can pass a list of regular expressions, of which those that match will be replaced with a scalar (list of regex -> regex).

  1. In [116]: df.replace([r'\s*\.\s*', r'a|b'], np.nan, regex=True)
  2. Out[116]:
  3. a b c
  4. 0 0 NaN NaN
  5. 1 1 NaN NaN
  6. 2 2 NaN NaN
  7. 3 3 NaN d

All of the regular expression examples can also be passed with the to_replace argument as the regex argument. In this case the value argument must be passed explicitly by name or regex must be a nested dictionary. The previous example, in this case, would then be:

  1. In [117]: df.replace(regex=[r'\s*\.\s*', r'a|b'], value=np.nan)
  2. Out[117]:
  3. a b c
  4. 0 0 NaN NaN
  5. 1 1 NaN NaN
  6. 2 2 NaN NaN
  7. 3 3 NaN d

This can be convenient if you do not want to pass regex=True every time you want to use a regular expression.

Note: Anywhere in the above replace examples that you see a regular expression a compiled regular expression is valid as well.

Numeric Replacement

replace() is similar to fillna().

  1. In [118]: df = pd.DataFrame(np.random.randn(10, 2))
  2. In [119]: df[np.random.rand(df.shape[0]) > 0.5] = 1.5
  3. In [120]: df.replace(1.5, np.nan)
  4. Out[120]:
  5. 0 1
  6. 0 -0.844214 -1.021415
  7. 1 0.432396 -0.323580
  8. 2 0.423825 0.799180
  9. 3 1.262614 0.751965
  10. 4 NaN NaN
  11. 5 NaN NaN
  12. 6 -0.498174 -1.060799
  13. 7 0.591667 -0.183257
  14. 8 1.019855 -1.482465
  15. 9 NaN NaN

Replacing more than one value is possible by passing a list.

  1. In [121]: df00 = df.values[0, 0]
  2. In [122]: df.replace([1.5, df00], [np.nan, 'a'])
  3. Out[122]:
  4. 0 1
  5. 0 a -1.02141
  6. 1 0.432396 -0.32358
  7. 2 0.423825 0.79918
  8. 3 1.26261 0.751965
  9. 4 NaN NaN
  10. 5 NaN NaN
  11. 6 -0.498174 -1.0608
  12. 7 0.591667 -0.183257
  13. 8 1.01985 -1.48247
  14. 9 NaN NaN
  15. In [123]: df[1].dtype
  16. Out[123]: dtype('float64')

You can also operate on the DataFrame in place:

  1. In [124]: df.replace(1.5, np.nan, inplace=True)

警告

When replacing multiple bool or datetime64 objects, the first argument to replace (to_replace) must match the type of the value being replaced. For example,

  1. s = pd.Series([True, False, True])
  2. s.replace({'a string': 'new value', True: False}) # raises
  3. TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str'

will raise a TypeError because one of the dict keys is not of the correct type for replacement.

However, when replacing a single object such as,

  1. In [125]: s = pd.Series([True, False, True])
  2. In [126]: s.replace('a string', 'another string')
  3. Out[126]:
  4. 0 True
  5. 1 False
  6. 2 True
  7. dtype: bool

the original NDFrame object will be returned untouched. We’re working on unifying this API, but for backwards compatibility reasons we cannot break the latter behavior. See GH6354 for more details.