[英]How to save a name as a variable when saving a Data frame file?
I have to save several files at a time.我必须一次保存多个文件。
It is saved as .txt using .to_csv.它使用.to_csv保存为.txt 。
The following method is used to save the Data Frames of position, energy, number, event, and height.以下方法用于保存position的Data Frames ,能量,数字,事件,高度。
position.to_csv('/HDD1/abc_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/abc_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/abc_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/abc_height.txt',index=False,sep=" ")
Let's check the save file name above.让我们检查上面的保存文件名。 They contain 'abc' .
它们包含'abc' 。 I want to replace 'abc' with the variable 'A = abc' without having to write it down many times.
我想用变量“A = abc”替换“abc”,而不必多次写下来。
In other words, it should be as follows.换句话说,它应该如下所示。
A = abc
postion.to_csv('/HDD1/A_position.txt',index=False,sep=" ")
energy.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
number.to_csv('/HDD1/A_energy.txt',index=False,sep=" ")
event.to_csv('/HDD1/A_event.txt',index=False,sep=" ")
height.to_csv('/HDD1/A_height.txt',index=False,sep=" ")
Is there a way to save files using variables as above?有没有办法像上面那样使用变量保存文件?
Are you looking for f-strings?您在寻找 F 弦吗?
A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")
can use an f-string.可以使用 f 弦。 Let
让
A = 'abc'
postion.to_csv(f'/HDD1/{A}_position.txt',index=False,sep=" ")
energy.to_csv(f'/HDD1/{A}_energy.txt',index=False,sep=" ")
number.to_csv(f'/HDD1/{A}_number.txt',index=False,sep=" ")
event.to_csv(f'/HDD1/{A}_event.txt',index=False,sep=" ")
height.to_csv(f'/HDD1/{A}_height.txt',index=False,sep=" ")
EDIT Aditional (don't know if pythonic) you can create dictionary with all your dataFrames and call this a simplier way:编辑附加(不知道是否 pythonic)你可以用你所有的数据帧创建字典并称之为更简单的方法:
dataFrames = {'position':position,
'energy':energy,
'number':number,
'event':event,
'height':height
}
A = 'abc'
dir = '/HHD1'
for key,val in dataFrames.items():
val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ")
The last one liner is the same as:最后一个班轮是一样的:
[val.to_csv(f'{dir}/{a}_{key}.txt',index=False,sep=" ") for key, val in dataFrames.items()]
I think the first way is more pythonic, but not sure我认为第一种方式更 pythonic,但不确定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.