![](/img/trans.png)
[英]How to partially replace a string in a column pandas Dataframe python
[英]How to replace a string in a dataframe column with another in Python Pandas?
我有一个名为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',' ')
但它没有用,没有错误信息,但comluns名称没有改变。
有什么想法请帮帮我吗?
谢谢
使用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: []
使用list-comprehension
:
df_cv.columns = [i.replace("_log","") for i in df_cv.columns]
您应该在集合中收集结果,或者至少处理它们
modified_cols=[]
for c in modify_cols:
modified_cols.append(c.replace('_log',' '))
或者更短的版本,使用列表推导 :
my_list = [c.replace('_log',' ') for c in df_cv.columns if c.find('_log')!=-1]
否则,您将在每个循环块后丢失每个c
变量。
=
使对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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.