简体   繁体   English

如何在 csv 文件中读取 Python 中的列作为变量名?

[英]How can I read in csv files with columns as variable names in Python?

This is a Python question.这是一个 Python 问题。 I have a csv file and would like to read that in. The first row in the file are strings and I would like to use them as variable names.我有一个 csv 文件并想读入。文件中的第一行是字符串,我想将它们用作变量名。 The other rows are integers and I would like them to be a vector of the name of the respective variable.其他行是整数,我希望它们成为相应变量名称的向量。

Thanks, Tim谢谢,蒂姆

you need to first extract your first row I suggest to count the characters of first row and use this code to read them你需要先提取你的第一行我建议计算第一行的字符并使用这段代码来阅读它们

f = open("demofile.txt", "r") print(f.read(5))#put your desired counted charactor inside f.read(n) f = open("demofile.txt", "r") print(f.read(5))#把你想要的计数字符放入 f.read(n)

when you successfully read it save it on variable and after saving use regex to split them with respect to ","当您成功读取它时,将其保存在变量中,并在保存后使用正则表达式将它们拆分为“,”

import re txt = "The rain in Spain" x = re.split("[,]", txt, 1) print(x) import re txt = "西班牙的雨" x = re.split("[,]", txt, 1) print(x)

after that use dictionary methods to attain your desired result.之后使用字典方法来获得您想要的结果。

You can simply use pandas to read.csv files.您可以简单地使用 pandas 来读取.csv 文件。 Just install pandas using 'pip install pandas'.只需使用“pip install pandas”安装 pandas。 Then use the following code:然后使用以下代码:

import pandas as pd

dataframe = pd.read_csv('data.csv')

# Returns a list containing names of the columns
column_names = list(dataframe.columns.values)

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

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