python assign value of dataframe by conditions

description: python assign or set value if conditions match

python assign or set value based on conditions

1
2
3
4
5
6
7
8
import pandas

data = pandas.DataFrame({"test": [10, 20, 30, 40], "a": [1, 1, 1, 2], "b": [0, 2, 2, 2]})
# test a b
# 0 10 1 0
# 1 20 1 2
# 2 30 1 2
# 3 40 2 2

filter the data with condtion 1

1
2
3
4
5
tmp = data[data["a"] == 1]
# test a b
# 0 10 1 0
# 1 20 1 2
# 2 30 1 2

filter the data with condition 2

1
2
3
4
tmp = tmp[tmp["b"] == 2]
# test a b
# 1 20 1 2
# 2 30 1 2

get the index of the data

1
2
indexes = tmp.index
# Int64Index([1, 2], dtype='int64')

change values by indexes and column name

1
2
3
4
5
6
data._set_value(indexes, 'test', 888888)
# test a b
# 0 10 1 0
# 1 888888 1 2
# 2 888888 1 2
# 3 40 2 2

more on search4fan.github.io