[英]How to create a DataFrame of a single column from a list where the first element is the column name in python
I have the below data in a csv and I am trying to create a dataframe of 1 column by selecting each column from the csv at a time. 我在csv中具有以下数据,并且我试图通过一次从csv中选择每一列来创建1列的数据框。
sv_m1 rev ioip
0 15.31 40
0 64.9 0
0 18.36 20
0 62.85 0
0 10.31 20
0 12.84 10
0 69.95 0
0 32.81 20
The list that I get, the first value is the column name and remaining are values. 我得到的列表,第一个值是列名,其余为值。
input_file = open('df_seg_sample.csv', 'r')
c_reader = csv.reader(input_file, delimiter=',')
#Read column
column = [x[1] for x in c_reader]
label = column[0]
column = column[1:]
df_column = pd.DataFrame.from_records(data = column,columns = label)
However this gives me an error: 但这给我一个错误:
TypeError: Index(...) must be called with a collection of some kind, 'sv_m1' was passed
core is actually the column name. 核心实际上是列名。
How can I create this df? 如何创建此df? The column name of the df will be the first element in the list and all other items in the list will be the column values.
df的列名将是列表中的第一个元素,列表中的所有其他项将是列值。
The reason for not using pandas.read_csv is: The dataframe is huge and hogs up a lot of memory. 不使用pandas.read_csv的原因是:数据帧很大,占用了大量内存。 So I want to read in a column at a time, do some processing and write it to another csv.
因此,我想一次读入一列,进行一些处理,然后将其写入另一个csv。
I think need read_csv
here with usecols
parameter for filter second column: 我认为需要
read_csv
在这里usecols
的过滤器第二列参数:
df = pd.read_csv('df_seg_sample.csv', usecols=[1])
print (df)
rev
0 15.31
1 64.90
2 18.36
3 62.85
4 10.31
5 12.84
6 69.95
7 32.81
But if want use your solution is necssary add []
for one item list for column name and use only DataFrame
contructor: 但是,如果要使用您的解决方案,请在列名的一个项目列表中添加
[]
,并且仅使用DataFrame
构造DataFrame
:
data = [x[1] for x in c_reader]
print (data)
['rev', '15.31', '64.9', '18.36', '62.85', '10.31', '12.84', '69.95', '32.81']
df = pd.DataFrame(data[1:], columns=[data[0]])
print (df)
rev
0 15.31
1 64.9
2 18.36
3 62.85
4 10.31
5 12.84
6 69.95
7 32.81
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.