How to Read CSV File from String into Pandas DataFrame


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 here.

Additional Resources

The following tutorials explain how to perform other common tasks in Python:

Pandas: How to Skip Rows when Reading CSV File
Pandas: How to Append Data to Existing CSV File
Pandas: How to Read CSV Without Headers
Pandas: Set Column Names when Importing CSV File

Leave a Reply

Your email address will not be published. Required fields are marked *