简体   繁体   English

更改部分 csv 字符串熊猫

[英]Change part of csv string panda

I would like to change the word consolidation (two times in the following string) with an other value with a variable or?我想用另一个带有变量的值来更改单词合并(以下字符串中的两次),还是? (ex. breakout/outofconsolidation/inside) (例如突破/脱离整合/内部)

Can I help me to achieve this, please?请问我可以帮我实现这个吗?

dfconsolidationcsv.to_csv(r'symbols\stocks_consolidation_sp500.csv', index = False)

a = ('breakout')
df{a}csv.to_csv(r'symbols\stocks_{a}_sp500.csv', index = False)

Unless there is a justifiable reason to be creating dynamic variable assignments, I would avoid doing so.除非有正当理由创建动态变量分配,否则我会避免这样做。 In this case, defining your DataFrame variables in a dict is probably sufficient:在这种情况下,在字典中定义 DataFrame 变量可能就足够了:

# store df in a dict instead of separate variables
df_dict = dict()
df_dict['consolidation'] = dfconslidationcv
df_dict['breakout'] = dfbreakoutcv
...

# invoke command for a specific variable
a = 'breakout'
df_dict[a].to_csv(r'symbols\stocks_%s_sp500.csv' % a, index = False)

Now, if there is an overwhelming reason why you HAVE to use pre-existing variable names that need to be changed dynamically, I think you can do something like this:现在,如果有一个压倒性的原因为什么您必须使用需要动态更改的预先存在的变量名称,我认为您可以执行以下操作:

a = 'breakout'
exec("df%scsv.to_csv(r'symbols\stocks_%s_sp500.csv', index=False)" % (a, a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM