Search code examples
pythonpandaslistcsviterable

How to use the "new line" command when converting a list into a dataframe?


I'm converting a string into a DataFrame, but when reading as csv, and then a list, the string iterates each letter as a new row in the DataFrame. How can I code where a new row should begin?

'overs' variable is a string:

BASKETBALL - NBA
SPREAD
MONEY
TOTAL
...

The following code returns a DataFrame with one letter per row.

df = pd.DataFrame(list(reader(overs)))

Returns:

col_name: 0 
data: 0      B
1      A
2      S
3      K
4      E
      ..
250     
251    P
252    L
253    A
254    Y
Name: 0, Length: 255, dtype: object

Solution

  • You could use .split('\n') which will return you a list with each element split on new line. But like others said, why not just use pandas' .read_csv()?

    import pandas as pd
    
    overs = '''BASKETBALL - NBA
    SPREAD
    MONEY
    TOTAL'''
    
    df = pd.DataFrame(overs.split('\n'))
    

    Output:

    print (df)
                      0
    0  BASKETBALL - NBA
    1            SPREAD
    2             MONEY
    3             TOTAL