![]() |
VOOZH | about |
Constructing a DataFrame in Pandas using string data means creating a pandas DataFrame where the values are strings instead of numbers. For example: making a table of student names and their cities using text values like "Alice", "Bob", "Delhi", "London".
Pandas easily converts this dictionary into a DataFrame. Each key represents a column name and values are stored as lists of strings.
Example: This example shows how to build a DataFrame directly from a dictionary of string lists.
Date Event Cost 0 10/2/2011 Music 10000 1 11/2/2011 Poetry 12000 2 12/2/2011 Theatre 5000 3 13/2/2011 Comedy 8000
This method involves creating a list of rows (sublists), where each sublist holds string values. Column names are added separately.
Example: This example creates a DataFrame using a list of lists with string values.
Date Event Cost 0 10/2/2011 Music 10000 1 11/2/2011 Poetry 12000 2 12/2/2011 Theatre 5000 3 13/2/2011 Comedy 8000
The StringIO() function from Python’s io module treats a string as a file-like object. This allows pd.read_csv() to parse it just like a real CSV file.
Example: This program loads a multi-line string into a DataFrame using StringIO().
Date Event Cost 0 10/2/2011 Music 10000 1 11/2/2011 Poetry 12000 2 12/2/2011 Theatre 5000 3 13/2/2011 Comedy 8000
The pd.read_clipboard() function lets users copy tabular data and load it directly into a DataFrame. It is convenient but less reliable since it depends on manual copying and clipboard availability.
Example: This example reads string data from the clipboard into a DataFrame.
Output
Date Event Cost
0 10/2/2011 Music 10000
1 11/2/2011 Poetry 12000
2 12/2/2011 Theatre 5000
3 13/2/2011 Comedy 8000