mr_sp
mr_sp

Reputation: 35

Set Pandas Value from an Index to an Index

I am trying to set value of 'D' from index 3-7 as 0, this is the code I have I'm getting a error.

df.iloc[3:7, 'D'] = 0

I also tried:

df.iloc[3:7]['D'] = 0
     A    B      C  D
0  foo  one  small  1
1  foo  one  large  2
2  foo  one  large  2
3  foo  two  small  3
4  foo  two  small  3
5  bar  one  large  4
6  bar  one  small  5
7  bar  two  small  6
8  bar  two  large  7

Upvotes: 0

Views: 63

Answers (3)

Muhammad Ammar Abid
Muhammad Ammar Abid

Reputation: 21

Try Using df.iloc[3:8, 3] = 0 because as you are using .iloc it takes only numbers/position so 3 here is column position starting from 0

Upvotes: 1

Oliver
Oliver

Reputation: 572

Try df.loc[df.index[3:7], "D"] = 0

EDIT: i think this will work! But make sure your index is set as index.

mask = (df.index >=3) & (df.index <=7)

df.loc[mask, "D"] = 0

P. S. : i had a similar problem today... It s night in Europe, I will check tomorrow but maybe it helps you earlier!

Upvotes: 2

Nicko
Nicko

Reputation: 362

df.loc[3:7, 'D'] = 0

The .iloc requires you to use the integer position of the column. .loc allows you to call it by name.

Upvotes: 2

Related Questions