how to create dataframe with for loop in rows
- User
how to create dataframe with for loop in rows
- Assistant
Here is an example of how to create a dataframe with for loop in rows using Python pandas library:
import pandas as pd # Define an empty dataframe df = pd.DataFrame(columns=['Name', 'Age', 'Gender', 'City']) # Define list of details details = [['John', 25, 'Male', 'New York'], ['Alex', 30, 'Male', 'Los Angeles'], ['Mary', 28, 'Female', 'Chicago'], ['Rachel', 22, 'Female', 'San Francisco']] # Iterate through the rows in the list of details and append them to the empty dataframe for row in details: df = df.append(pd.Series(row, index=['Name', 'Age', 'Gender', 'City']), ignore_index=True) # Print the dataframe print(df)Output:
Name Age Gender City 0 John 25 Male New York 1 Alex 30 Male Los Angeles 2 Mary 28 Female Chicago 3 Rachel 22 Female San FranciscoIn this code, we first create an empty dataframe with specific column headers using the
pd.DataFrame()method. Then we define a list of rows containing the data to be added to the dataframe.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.