[英]How to insert a column at the beginning of csv file using python
Please inform how can I append a column with all 1s at the beginning of the csv file?请告知如何在 csv 文件的开头附加一个全为 1 的列?
orginal:
y z
1 5
2 6
3 7
Required:
x y z
1 1 5
1 2 6
1 3 7
If you're using a library like pandas,如果你使用的是像 Pandas 这样的库,
df.insert(0, "col1", [100, 100], allow_duplicates=True)
0 indicates the column you're adding. 0 表示您要添加的列。 col1 is the name of that column, and the array is the values you're inserting. col1 是该列的名称,数组是您要插入的值。
As referenced here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.insert.html此处引用: https : //pandas.pydata.org/docs/reference/api/pandas.DataFrame.insert.html
pandas
is a great lib to read csv and manipulate its data. pandas
是一个很好的库,可以读取 csv 并操作其数据。 Read the data, add the x-1
column, then dump the content again读取数据,添加x-1
列,然后再次转储内容
import pandas as pd
df = pd.read_csv("export.csv")
df['x'] = 1
df = df[['x', 'y', 'z']] # reorder cols
df.to_csv("export.csv", index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.