文字列の外観に基づいて文字列を Pandas DataFrame に変換する 3 つの方法を以下に示します。
(1) 列名を含む複数行の文字列
import pandas as pd
from io import StringIO
my_string = """col_1,col_2,col_3
11,22,33
xx,yy,zz
4,5,6
"""
data = StringIO(my_string)
df = pd.read_csv(data, sep=",")
print(df)
文字列はPandas DataFrameに変換されます

(2)列名を含む1行の文字列
import pandas as pd
my_string = "col_1,col_2,col_3,11,22,33,xx,yy,zz,4,5,6"
# Split the string based on a comma separator
my_list = my_string.split(",")
# Split the list into equally-sized chunks of three
my_list_of_lists = [my_list[x:x + 3] for x in range(0, len(my_list), 3)]
# Break the list of lists into the data without the columns, and just the columns
list_of_lists_without_columns = my_list_of_lists[1:]
list_columns = my_list_of_lists[0]
# Create the DataFrame
df = pd.DataFrame(list_of_lists_without_columns, columns=list_columns)
print(df)
結果は同じ DataFrame になります。

(3)列名を含まない1行の文字列
import pandas as pd
my_string = "11,22,33,xx,yy,zz,4,5,6"
# Split the string based on a comma separator
my_list = my_string.split(",")
# Split the list into equally-sized chunks of three
my_list_of_lists = [my_list[x:x + 3] for x in range(0, len(my_list), 3)]
# Create a list of columns
list_columns = ["col_1", "col_2", "col_3"]
# Create the DataFrame
df = pd.DataFrame(my_list_of_lists, columns=list_columns)
print(df)
結果:






