[英]Write in the next column of CSV file in python
I have a simple code that should write values in two columns, I would like to have the results shown as: 0.48 2.71 But I can only write in rows, how do I write the rows in the second column (I want to have the fines percentages in one column and 'X' in the second column)?我有一个简单的代码应该在两列中写入值,我希望结果显示为:0.48 2.71 但我只能写入行,如何在第二列中写入行(我想要罚款一列中的百分比和第二列中的“X”)? your help is much appreciated.
非常感谢您的帮助。 Here is the code:
这是代码:
import csv
finespacking = 0.55
d63fine= 2
coarsepacking= 0.6
d63coarse = 5
x=[]
percentage_fines_agg= [0.48,0.49,0.50,0.51,0.52,0.53,0.54,0.55,0.56,0.57,0.58,0.59,0.60]
rows = [[data] for data in x]
for item in percentage_fines_agg:
with open ('tempmix.csv') as temp_mix_file:
x= (item/(1-item))* (coarsepacking/finespacking)/(1-coarsepacking)
writer= csv.writer(temp_mix_file)
writer.writerows(rows)
You can use pandas您可以使用 pandas
pip install pandas
pip install pandas
and then in the script然后在脚本中
import pandas as pd
df = pd.read_csv('tempmix.csv')
for item in percentage_fines_agg:
df["second_column_name"] = the_value_you_need_to_store
# And if u want to save the new created file :
df.to_csv("new_file_name.csv")
You will fine the new file called new_file_name.csv in the working directory您将在工作目录中创建名为 new_file_name.csv 的新文件
If you want to do this without Pandas you could do something like:如果您想在没有 Pandas 的情况下执行此操作,您可以执行以下操作:
import csv
finespacking = 0.55
coarsepacking = 0.6
factor = (coarsepacking / finespacking) / (1 - coarsepacking)
with open("tempmix.csv", "w", newline="") as out_file:
csv_writer = csv.writer(out_file)
for x in range(48, 60 + 1):
x /= 100
y = factor * x / (1 - x)
csv_writer.writerow([x, y])
compared to your snippet, the key modifications are:与您的代码段相比,主要修改是:
csv.writer()
outside of the loopcsv.writer()
csv_writer.writerow()
to write each row at oncecsv_writer.writerow()
一次写入每一行percentage_fines_agg
and the value computed form itpercentage_fines_agg
的值和从它计算的值I also took the liberty of introducing the following non-mandatory but helpful modification:我还冒昧地介绍了以下非强制性但有用的修改:
factor
outside of the loop)factor
)percentage_fines_agg
values dynamically.percentage_fines_agg
值。 If you want to use Pandas, this is much simpler to write:如果要使用 Pandas,这样写起来就简单多了:
import pandas as pd
finespacking = 0.55
coarsepacking = 0.6
factor = (coarsepacking / finespacking) / (1 - coarsepacking)
df = pd.DataFrame(data=range(48, 60 + 1))
df[0] /= 100
df[1] = factor * df[0] / (1 - df[0])
df.to_csv("tempmix.csv", header=False, index=False)
In both cases, the content of tempmix.csv
is the following:在这两种情况下,
tempmix.csv
的内容如下:
0.48,2.517482517482517
0.49,2.620320855614973
0.5,2.727272727272727
0.51,2.8385899814471243
0.52,2.9545454545454546
0.53,3.0754352030947776
0.54,3.2015810276679844
0.55,3.3333333333333335
0.56,3.4710743801652897
0.57,3.6152219873150093
0.58,3.7662337662337655
0.59,3.9246119733924605
0.6,4.09090909090909
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.