Table of Contents
To read a csv file from a string in pandas dataframe, we can use the read_csv method, passing the string as a parameter to the method. This will create a DataFrame object with the data from the CSV file. We can then use the DataFrame’s methods and properties to access and manipulate the data.
You can use the following basic syntax to read a CSV file from a string into a pandas DataFrame:
import pandas as pd import io df = pd.read_csv(io.StringIO(some_string), sep=",")
The following examples show how to use this syntax in practice.
Example 1: Read CSV File from String with Commas as Separators
The following code shows how to read a CSV file from a string (with commas as separators) into a pandas DataFrame:
import pandas as pd import io some_string="""team,points,rebounds A,22,10 B,14,9 C,29,6 D,30,2 E,22,9 F,31,10""" #read CSV string into pandas DataFrame df = pd.read_csv(io.StringIO(some_string), sep=",") #view resulting DataFrame print(df) team points rebounds 0 A 22 10 1 B 14 9 2 C 29 6 3 D 30 2 4 E 22 9 5 F 31 10
The resulting pandas DataFrame contains the values from the CSV string.
Example 2: Read CSV File from String with Semicolon as Separators
The following code shows how to read a CSV file from a string (with semicolons as separators) into a pandas DataFrame:
import pandas as pd import io some_string="""team;points;rebounds A;22;10 B;14;9 C;29;6 D;30;2 E;22;9 F;31;10""" #read CSV string into pandas DataFrame df = pd.read_csv(io.StringIO(some_string), sep=";") #view resulting DataFrame print(df) team points rebounds 0 A 22 10 1 B 14 9 2 C 29 6 3 D 30 2 4 E 22 9 5 F 31 10
The resulting pandas DataFrame contains the values from the CSV string.
Example 3: Read CSV File from String with No Header
The following code shows how to read a CSV file from a string (with no header row) into a pandas DataFrame:
import pandas as pd import io some_string="""A;22;10 B;14;9 C;29;6 D;30;2 E;22;9 F;31;10""" #read CSV string into pandas DataFrame df = pd.read_csv(io.StringIO(some_string), sep=";", header=None) #view resulting DataFrame print(df) 0 1 2 0 A 22 10 1 B 14 9 2 C 29 6 3 D 30 2 4 E 22 9 5 F 31 10
By using the argument header=None, we told pandas not to use the first row as the header row.
By default, pandas uses a range of numerical values (0, 1, 2) as the column names for the DataFrame.
Note: You can find the complete documentation for the pandas read_csv() function .
The following tutorials explain how to perform other common tasks in Python: