0

I have a dataframe with lots of values (just either 0 or 1). I have the table currently with just 0s and if a certain intersection (of that row and column) is true, I want to change that value to 1. For example, if my dataframe looks like this and I want to access the X element to assign a particular value to it.

ID | 1 | 2 | 3 | 4 | 5
A  |   |   |   |   |
B  |   |   | X |   |
C  |   |   |   |   |

The code I used is df[3][df['ID'] == 'B'] = 1, however instead of just changing that particular value (marked X in the dataframe) to 1, it changes all the values in the column named 3.

Am I using the wrong syntax or logic here? Any answers are appreciated, thanks!

shshshsh
  • 35
  • 5
  • `df['ID'] == 'B'` returns a bool, yeah ? – EvgenyKolyakov May 29 '22 at 09:25
  • Maybe just use `df[3]['B'] = 1` or `df[3][df['ID']] = 1` – EvgenyKolyakov May 29 '22 at 09:26
  • 1
    Does this answer your question? [Set value for particular cell in pandas DataFrame using index](https://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe-using-index) – Joooeey May 29 '22 at 10:26
  • you could create minimal working code with example data in code (as `df = DataFrame(...)`) - so we could see if you use it correctly in this code, and if you keep data in correct way. And we could use this code to test solutions. – furas May 29 '22 at 11:47
  • maybe first you should use `print()` to see what you really selected using `df[3][df['ID'] == 'B']` – furas May 29 '22 at 11:50

2 Answers2

0

I made a quick example:

df = pd.DataFrame(np.arange(9).reshape(3,3), index='A B C'.split(), columns='1 2 3'.split())

You can use replace for a specific value

df['2'].replace(4, 'X', inplace=True)

But your approach also worked in my example

df['3'][df.index == 'B'] = 42
Dura
  • 51
  • 2
  • 10
0

Another fast and simple method:

#original DF:

df1 = pd.DataFrame({'A': [0,0,0],\
                    'B': [0,0,0],\
                    'C': [0,0,0]})
df1 = df1.transpose()
df1
index 0 1 2
A 0 0 0
B 0 0 0
C 0 0 0

Code to locate the cell and set the new value with the .at():

df1.at['B', 1] = '1'
df1
index 0 1 2
A 0 0 0
B 0 1 0
C 0 0 0
Drakax
  • 1,305
  • 3
  • 9