Code:
import pandas as pd
def map_val(df, rules):
for column_name in rules.keys():
column = df[column_name]
rule_for_this_column = rules.get(column_name)
column[:] = [rule_for_this_column(value) for value in column]
def a_rule(value):
digit = float(value)
if digit > 1:
return 1
else:
return 0
def b_rule(value):
if value > 8:
return 1
else:
return 0
table = {
'a': ['1', '2', '3', '4', '5'],
'b': [6, 7, 8, 9, 10],
'c': [11, 12, 13, 14, 15],
}
df = pd.DataFrame(table)
print(df)
rules = {
'a': a_rule,
'b': b_rule
}
map_val(df, rules)
print(df)
Output:
a b c
0 1 6 11
1 2 7 12
2 3 8 13
3 4 9 14
4 5 10 15
my/source/path/test.py:8: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
column[:] = [rule_for_this_column(value) for value in column]
a b c
0 0 0 11
1 1 0 12
2 1 0 13
3 1 1 14
4 1 1 15
I want to modify each series that has label of keys in dictionary rules
, by applying corresponding mapper function(the value of rules
) to every single value in that series.
I've read the link provided in warning message and changed my code as below:
# column[:] = [rule_for_this_column(value) for value in column]
for idx, value in column.items():
column.loc[idx] = rule_for_this_column(value)
While the warning still exists.