How to Convert a List to a DataFrame Row in Python?

How to Convert a List to a DataFrame Row in Python?

To convert a list to a DataFrame row in Python using pandas, you can simply pass the list to the DataFrame constructor. Here's how you can do it:

  1. Basic Conversion:

    import pandas as pd data = [1, 'Alice', 25] df = pd.DataFrame([data], columns=['ID', 'Name', 'Age']) print(df) 

    Here, the list data is wrapped within another list ([data]) to make it a single row in the DataFrame. The columns parameter is used to provide column names.

  2. Appending to an Existing DataFrame:

    If you already have an existing DataFrame and you want to append a new row to it, you can use the loc indexer or the append method:

    Using loc:

    import pandas as pd df = pd.DataFrame(columns=['ID', 'Name', 'Age']) # Add new row using loc data = [1, 'Alice', 25] df.loc[len(df)] = data print(df) 

    Using append:

    import pandas as pd df = pd.DataFrame(columns=['ID', 'Name', 'Age']) # Add new row using append data = [1, 'Alice', 25] df = df.append(pd.Series(data, index=df.columns), ignore_index=True) print(df) 
  3. Conversion of Multiple Lists:

    If you have multiple lists that you want to convert to DataFrame rows:

    import pandas as pd data = [[1, 'Alice', 25], [2, 'Bob', 30], [3, 'Charlie', 35]] df = pd.DataFrame(data, columns=['ID', 'Name', 'Age']) print(df) 

By using the above methods, you can easily convert a list or multiple lists into DataFrame rows in Python with pandas.


More Tags

ord array-merge sql-server-2008 javascript-intellisense load-testing lines egit codeigniter-3 printing-web-page pkcs#11

More Programming Guides

Other Guides

More Programming Examples