0

I'm new to python and pandas and I need some ideas. Say I have the following DataFrame:

0 1 2 3 4 5
1 5 5 5 5 5
2 5 5 5 5 5
3 5 5 5 5 5
4 5 5 5 5 5

I want to iterate through each row and change the values of specific columns. Say I wanted to change all of the values in columns (2,3,4) to a 3.

This is what I've tried, am I going down the right path?

for row in df.iterrows():
        for col in range(2, 4):
            df.set_value('row', 'col', 3)

EDIT: Thanks for the responses. The simple solutions are obvious, but what if I wanted to change the values to this... for example:

0  1  2  3  4  5
1  1  2  3  4  5
2  6  7  8  9  10
3  11 12 13 14 15
4  16 17 18 19 20
embedded.95
  • 63
  • 1
  • 8

2 Answers2

2

If you are using a loop when working with dataframes, you are almost always not on the right track.

For this you can use a vectorized assignment:

df[[2, 3, 4]] = 3

Example:

df = pd.DataFrame({1: [1, 2], 2:  [1, 2]})
print(df)
#     1  2
#  0  1  1
#  1  2  2

df[[1, 2]] = 3

print(df)
#     1  2
#  0  3  3
#  1  3  3
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Yes, this would be correct. But what if I wanted to apply this to 2000 rows of data, where the assigned values are different for each row. It now becomes more complicated, hence the loop. I created this dumbed down example, but I assume the principle would be the same. – embedded.95 Nov 19 '18 at 11:45
  • @embedded.95 Then that is an entirely different question which has been asked and answered many times before. Use pandas indexing or `np.where`. – DeepSpace Nov 19 '18 at 11:49
2

you can do this

df.iloc[:,1] = 3 #columns 2 
df.iloc[:,2] = 3 
df.iloc[:,3] = 3 
Sociopath
  • 13,068
  • 19
  • 47
  • 75
runzhi xiao
  • 186
  • 6