我有一个名为 df_cv 的数据框,其中的列包含此字符串 _log 。 我想从数据框中每一列的名称中删除 _log 所以我很喜欢:
modify_cols=[]
for c in df_cv.columns:
if c.find("_log") != -1:
modify_cols.append(c)
for c in modify_cols:
c = c.replace('_log',' ')
但是它不起作用,没有错误消息,但是名称没有改变。
有什么想法可以帮助我吗?
谢谢
答案 0 :(得分:3)
使用str.replace
:
df_cv = pd.DataFrame(columns=['col1','col2_log','1_log'])
df_cv.columns=df_cv.columns.str.replace('_log', '')
print (df_cv)
Empty DataFrame
Columns: [col1, col2, 1]
Index: []
答案 1 :(得分:0)
使用GLOB
:
list-comprehension
答案 2 :(得分:0)
您应在集合中收集结果,或至少对其进行处理
modified_cols=[]
for c in modify_cols:
modified_cols.append(c.replace('_log',' '))
或更短的版本,使用list comprehensions:
my_list = [c.replace('_log',' ') for c in df_cv.columns if c.find('_log')!=-1]
否则,您将在每个循环块之后丢失每个c
变量。
答案 3 :(得分:0)
=
使对c
的引用成为一个新字符串,但是modify_cols
所引用的字符串仍然是原始字符串。而且由于字符串是不可变的,所以您不能这样:
s = [['a_log'], ['b_log']]
for i in s:
# i reference to the mutable list
i[0] = i[0].replace('_log', '')
# now s is [['a'], ['b']]
您可以使用列表理解:
modify_cols = [c.replace('_log',' ') for c in modify_cols]