Home > Software engineering >  Setting particular values in a dataframe
Setting particular values in a dataframe

Time:05-30

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!

CodePudding user response:

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

CodePudding user response:

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
  • Related