如果您想用新创建的 List_of_dummy_names(带有 'BINARY_'+column_name 的元素)重命名 pandas 数据框列,那么您可以按照我的回答。
让我们说
cv = list(df.columns.values)
#cv = ['aword', 'bword', 'c']
search_String = 'word'
replace_dict = dict(zip(cv,['BINARY_'+x if search_String in x else x for x in cv]))
#{'aword': 'BINARY_aword', 'bword': 'BINARY_bword', 'c': 'c'}
#Then in pandas dataframe rename method, use this dictinary
new_df = df.rename(col=replace_dict)
同时检查您是否可以使用以下内容
List_of_dummy_names = ['BINARY_'+x for x in cv if search_String in x ]
#['BINARY_aword', 'BINARY_bword'] #filters the element having 'word' in them and prefixed with 'BINARY_'
检查你是否需要这个(因为我对“你在找什么”感到困惑)
#df has only one column named 'col_to_replace'
col_to_replace
aword
bword
c
df['col_to_replace'] = ['BINARY_'+x if search_String in x else x for x in df['col_to_replace']]
#col_to_replace
BINARY_aword #prefixed
BINARY_bword #prefixed
c #word not found, so as it was
现在您在列表中获得了新的列名列表。
List_of_dummy_names #['BINARY_aword', 'BINARY_bword']
#loop over it and create new columns in existing dataframe
for col_Name in List_of_dummy_names:
df[col_Name] = 'default_value_1' #it will create new column "BINARY_aword" and all the row_values as string 'default_value_1' for first loop and in 2nd loop new column "BINARY_aword" with all values as 'default_value_1'.
如果您在 len(list) == len(df) 的列表中已有值,则将该列表指定为 df[col_Name] = list_of_values_having_same_length_as_DF