如何在python中从csv格式字符串获取数据帧格式
假设在python中有csv格式的字符串a='1,2,3\r4,5,6\r7,8,9\r'。 如何从变量a中获取数据帧[[1,2,3]、[4,5,6]、[7,8,9]]的“3行x 3列” 谢谢。试试这个:如何在python中从csv格式字符串获取数据帧格式,python,python-3.x,pandas,csv,dataframe,Python,Python 3.x,Pandas,Csv,Dataframe,假设在python中有csv格式的字符串a='1,2,3\r4,5,6\r7,8,9\r'。 如何从变量a中获取数据帧[[1,2,3]、[4,5,6]、[7,8,9]]的“3行x 3列” 谢谢。试试这个: temp = [i.split(',') for i in a.split('/r')] result = [list(map(int, i)) for i in temp[:-1]] 试试这个: temp = [i.split(',') for i in a.split('/r')] re
temp = [i.split(',') for i in a.split('/r')]
result = [list(map(int, i)) for i in temp[:-1]]
试试这个:
temp = [i.split(',') for i in a.split('/r')]
result = [list(map(int, i)) for i in temp[:-1]]
您可以使用
io
模块从字符串创建一个字符串。假设您有一个实际为csv格式的字符串,则:
In [1]: import io
In [2]: import pandas as pd
In [3]: s = '1,2,3\n4,5,6\n7,8,9'
In [4]: print(s)
1,2,3
4,5,6
7,8,9
像使用文件对象一样使用io.StringIO
:
In [5]: pd.read_csv(io.StringIO(s))
Out[5]:
1 2 3
0 4 5 6
1 7 8 9
In [6]: pd.read_csv(io.StringIO(s), header=None)
Out[6]:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
您可以使用
io
模块从字符串创建一个字符串。假设您有一个实际为csv格式的字符串,则:
In [1]: import io
In [2]: import pandas as pd
In [3]: s = '1,2,3\n4,5,6\n7,8,9'
In [4]: print(s)
1,2,3
4,5,6
7,8,9
像使用文件对象一样使用io.StringIO
:
In [5]: pd.read_csv(io.StringIO(s))
Out[5]:
1 2 3
0 4 5 6
1 7 8 9
In [6]: pd.read_csv(io.StringIO(s), header=None)
Out[6]:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
另一种选择是: 输入:
a='1,2,3\n4,5,6\n7,8,9'
print a
1,2,3
4,5,6
7,8,9
转换为列表,然后转换为df:
import re
import pandas as pd
my_list = re.split("[,\n]", a)
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print df
输出:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
另一种选择是: 输入:
a='1,2,3\n4,5,6\n7,8,9'
print a
1,2,3
4,5,6
7,8,9
转换为列表,然后转换为df:
import re
import pandas as pd
my_list = re.split("[,\n]", a)
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print df
输出:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
抱歉,它应该是反斜杠,因此\r表示行的结尾。我修改了帖子。对不起,它应该是反斜杠,所以\r,表示行尾。我修改了帖子。