Python将逗号分隔的列表转换为 pandas 数据框 [英] Python convert comma separated list to pandas dataframe
问题描述
我正在努力将以逗号分隔的列表转换为多列(7)数据帧.
I am struggling to convert a comma separated list into a multi column (7) data-frame.
print (type(mylist))
<type 'list'>
Print(mylist)
['AN,2__AAS000,26,20150826113000,-283.000,20150826120000,-283.000', 'AN,2__AE000,26,20150826113000,0.000,20150826120000,0.000',.........
以下内容创建了一个单列框架:
The following creates a frame of a single column:
df = pd.DataFrame(mylist)
我已经查看了Pandas内置的csv功能,但是我的csv数据保存在一个列表中.我怎样才能简单地将列表转换成7列数据框.
I have reviewed the inbuilt csv functionality for Pandas, however my csv data is held in a list. How can I simply covert the list into a 7 column data-frame.
谢谢.
推荐答案
您需要拆分列表中的每个字符串:
You need to split each string in your list:
import pandas as pd
df = pd.DataFrame([sub.split(",") for sub in l])
print(df)
输出:
0 1 2 3 4 5 6
0 AN 2__AS000 26 20150826113000 -283.000 20150826120000 -283.000
1 AN 2__A000 26 20150826113000 0.000 20150826120000 0.000
2 AN 2__AE000 26 20150826113000 -269.000 20150826120000 -269.000
3 AN 2__AE000 26 20150826113000 -255.000 20150826120000 -255.000
4 AN 2__AE00 26 20150826113000 -254.000 20150826120000 -254.000
如果您知道要在csv中跳过多少行,则可以使用skiprows=lines_of_metadata
使用read_csv完成所有操作:
If you know how many lines to skip in your csv you can do it all with read_csv using skiprows=lines_of_metadata
:
import pandas as pd
df = pd.read_csv("in.csv",skiprows=3,header=None)
print(df)
或者,如果元数据的每一行都以某个特定字符开头,则可以使用注释:
Or if each line of the metadata starts with a certain character you can use comment:
df = pd.read_csv("in.csv",header=None,comment="#")
如果需要指定多个字符,则可以将itertools.takewhile
组合在一起,这将删除以xxx
开头的行:
If you need to specify more then one character you can combine itertools.takewhile
which will drop lines starting with xxx
:
import pandas as pd
from itertools import dropwhile
import csv
with open("in.csv") as f:
f = dropwhile(lambda x: x.startswith("#!!"), f)
r = csv.reader(f)
df = pd.DataFrame().from_records(r)
使用您的输入数据,添加以#!!开头的几行:
Using your input data adding some lines starting with #!!:
#!! various
#!! metadata
#!! lines
AN,2__AS000,26,20150826113000,-283.000,20150826120000,-283.000
AN,2__A000,26,20150826113000,0.000,20150826120000,0.000
AN,2__AE000,26,20150826113000,-269.000,20150826120000,-269.000
AN,2__AE000,26,20150826113000,-255.000,20150826120000,-255.000
AN,2__AE00,26,20150826113000,-254.000,20150826120000,-254.000
输出:
0 1 2 3 4 5 6
0 AN 2__AS000 26 20150826113000 -283.000 20150826120000 -283.000
1 AN 2__A000 26 20150826113000 0.000 20150826120000 0.000
2 AN 2__AE000 26 20150826113000 -269.000 20150826120000 -269.000
3 AN 2__AE000 26 20150826113000 -255.000 20150826120000 -255.000
4 AN 2__AE00 26 20150826113000 -254.000 20150826120000 -254.000
这篇关于Python将逗号分隔的列表转换为 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!