embedded.95
embedded.95

Reputation: 63

Python: Changing values in a DataFrame

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

Upvotes: 0

Views: 238

Answers (2)

DeepSpace
DeepSpace

Reputation: 81684

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

Upvotes: 2

runzhi xiao
runzhi xiao

Reputation: 184

you can do this

df.iloc[:,1] = 3 #columns 2 
df.iloc[:,2] = 3 
df.iloc[:,3] = 3 

Upvotes: 2

Related Questions