0

Look at the following code:

import numpy as np
import pandas as pd

np.random.seed(42)
arr = np.random.randint(1, 11, (5, 5)).astype(np.float)
df = pd.DataFrame(arr)

>>> df
Out[49]: 
      0    1     2    3    4
0   7.0  4.0   8.0  5.0  7.0
1  10.0  3.0   7.0  8.0  5.0
2   4.0  8.0   8.0  3.0  6.0
3   5.0  2.0   8.0  6.0  2.0
4   5.0  1.0  10.0  6.0  9.0

rows, cols = [0, 2], [1, 3]
arr[rows, cols] = np.nan
df = pd.DataFrame(arr)

>>> df
Out[50]: 
      0    1     2    3    4
0   7.0  NaN   8.0  5.0  7.0
1  10.0  3.0   7.0  8.0  5.0
2   4.0  8.0   8.0  NaN  6.0
3   5.0  2.0   8.0  6.0  2.0
4   5.0  1.0  10.0  6.0  9.0

Is there a way to replace the values at the defined indices with e.g. NaN that does not require the conversion of the dataframe to a numpy array?

zwithouta
  • 1,319
  • 1
  • 9
  • 22
  • Are you only interested in replacing `nan` values? This [post](https://stackoverflow.com/questions/13295735/how-can-i-replace-all-the-nan-values-with-zeros-in-a-column-of-a-pandas-datafra) will should be useful if so. – busybear Jan 30 '19 at 18:45
  • Thanks for the response! No Im interested in a numpy-like replacement using the indices of rows & columns (not index and column names, but the numerical indices) – zwithouta Jan 30 '19 at 19:25

2 Answers2

1

Try this:

df.values[rows, cols]
Colonder
  • 1,556
  • 3
  • 20
  • 40
  • `values` will actually give a numpy array. – busybear Jan 30 '19 at 18:47
  • This is the shortcut I have searched for. `df.values` outputs an numpy array, but `df.values[rows, cols] = np.nan` updates the dataframe! This allows me to replace values in the dataframe by using numerical indices (that is I don't have to care about the labeling of the rows/columns of the dataframe) – zwithouta Jan 30 '19 at 19:44
0

Using lookup

df.lookup(rows,cols)
Out[810]: array([4, 3])
BENY
  • 317,841
  • 20
  • 164
  • 234
  • This is essentially doing the same things as in my answer, or iterating over the indices using zip() and getting each value at a time – Colonder Jan 30 '19 at 15:28
  • @Colonder not always same , this one is index and columns base, .values is position base , so close but not same . – BENY Jan 30 '19 at 15:34
  • Thanks for the reply. I edited the question a little bit. @Colonder indeed came up with what I was looking for – zwithouta Jan 30 '19 at 19:45