Python 读取csv文件pandas时给出列名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31645466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Give column name when read csv file pandas
提问by markov zain
This is the example of my dataset.
这是我的数据集的示例。
>>> user1 = pd.read_csv('dataset/1.csv')
>>> print(user1)
0 0.69464 3.1735 7.5048
0 0.030639 0.14982 3.48680 9.2755
1 0.069763 -0.29965 1.94770 9.1120
2 0.099823 -1.68890 1.41650 10.1200
3 0.129820 -2.17930 0.95342 10.9240
4 0.159790 -2.30180 0.23155 10.6510
5 0.189820 -1.41650 1.18500 11.0730
How to push down the first column and add the names column [TIME, X, Y, and Z] on the first column.
如何下推第一列并在第一列上添加名称列 [TIME, X, Y, and Z]。
The desired output is like this:
所需的输出是这样的:
TIME X Y Z
0 0 0.69464 3.1735 7.5048
1 0.030639 0.14982 3.48680 9.2755
2 0.069763 -0.29965 1.94770 9.1120
3 0.099823 -1.68890 1.41650 10.1200
4 0.129820 -2.17930 0.95342 10.9240
5 0.159790 -2.30180 0.23155 10.6510
6 0.189820 -1.41650 1.18500 11.0730
采纳答案by WillemM
I'd do it like this:
我会这样做:
colnames=['TIME', 'X', 'Y', 'Z']
user1 = pd.read_csv('dataset/1.csv', names=colnames, header=None)
回答by jitsm555
If we are directly use data from csv it will give combine data based on comma separation value as it is .csv file.
如果我们直接使用来自 csv 的数据,它将根据逗号分隔值给出组合数据,因为它是 .csv 文件。
user1 = pd.read_csv('dataset/1.csv')
If you want to add column names using pandas, you have to do something like this. But below code will not show separate header for your columns.
如果你想使用 Pandas 添加列名,你必须做这样的事情。但是下面的代码不会为您的列显示单独的标题。
col_names=['TIME', 'X', 'Y', 'Z']
user1 = pd.read_csv('dataset/1.csv', names=col_names)
To solve above problem we have to add extra filled which is supported by pandas, It is header=None
为了解决上述问题,我们必须添加熊猫支持的额外填充,即header=None
user1 = pd.read_csv('dataset/1.csv', names=col_names, header=None)
回答by Mahendra
user1 = pd.read_csv('dataset/1.csv', names=['Time', 'X', 'Y', 'Z'])
names parameter in read_csv function is used to define column names. If you pass extra name in this list, it will add another new column with that name with NaN values.
read_csv 函数中的名称参数用于定义列名称。如果您在此列表中传递额外的名称,它将添加另一个具有 NaN 值的名称的新列。
header=None is used to trim column names is already exists in CSV file.
header=None 用于修剪 CSV 文件中已存在的列名。
回答by Hariharan AR
we can do it with a single line of code.
我们可以用一行代码来完成。
user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)