我想根据另一列('col_search')中的值更改pd.DataFrame中列('col_change')的值(转换为'新值')。对于单个更改,我有一个解决方案,但我正在寻找多个搜索值的解决方案。
预期单值的示例:
import numpy as np
import pandas as pd
my_array = np.array([[1,2,3,4,5,6,7,8,9,10],[11,22,33,44,55,66,77,88,99,100]])
my_df = pd.DataFrame(my_array, columns = ['col_change', 'col_search'])
my_df.col_change[my_df.col_search == 22] = 'new value'
print(my_df)
多值的示例不能像预期的那样工作:“in”运算符在这里不起作用。
import numpy as np
import pandas as pd
my_array = np.array([[1,2,3,4,5,6,7,8,9,10],[11,22,33,44,55,66,77,88,99,100]])
my_df = pd.DataFrame(my_array, columns = ['col_change', 'col_search'])
list_of_search = [33, 44, 55]
my_df.col_change[my_df.col_search in list_of_search] = 'new value'
print(my_df)
答案 0 :(得分:0)
使用df.columns.isin
In [1083]: my_df.loc[my_df.col_search.isin([33, 44, 55]), 'col_change'] = 'new value'
In [1084]: my_df
Out[1084]:
col_change col_search
0 1 11
1 2 22
2 new value 33
3 new value 44
4 new value 55
5 6 66
6 7 77
7 8 88
8 9 99
9 10 100