[英]Pandas dataframe into a list of lists
I am trying too read a csv file and convert it into a 2d array according to the following principle: [ [12, 22],[11,21] ] etc. I used the following code我也在尝试读取 csv 文件并根据以下原则将其转换为二维数组:[ [12, 22],[11,21] ] 等。我使用了以下代码
import pandas as pd
fields = ['month', '8.2']
data = pd.read_csv('demand_with_station_id.csv', index_col=1 ,usecols = fields)
df = pd.DataFrame(data)
print(df)
supralist = []
for indx, val in df.iterrows():
lst = [val[indx]['month'], val[indx]['8.2']]
supralist.append(lst)
print(supralist)
It results in an error.这会导致错误。 I want not to read the first four rows into the list, how do I do that?
我不想将前四行读入列表,我该怎么做? The csv file is a bit non-standard and it looks like this: csv
csv 文件有点不标准,看起来像这样: csv
I get the following error:我收到以下错误:
Traceback (most recent call last):
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyError: 'Friday'
you can directly use values.tolist() on the columns which you want to be list of list.您可以直接在要成为列表列表的列上使用 values.tolist() 。
you don't need to loop and create the list.你不需要循环和创建列表。
data_list=df[['month', '8.2']].values.tolist()
to exclude the first 4 records from the list you can now remove it form data_list要从列表中排除前 4 条记录,您现在可以从 data_list 中删除它
data_list=data_list[4:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.