Constructing pandas DataFrame from values in variables gives ValueError
Here is an example code snippet that demonstrates the issue:
import pandas as pd
# Assign values to variables
name = 'John'
age = 30
city = 'New York'
# Attempt to create a DataFrame using the variables
df = pd.DataFrame({'Name': name, 'Age': age, 'City': city})
In this example, we are trying to create a DataFrame using the values stored in the variables name
, age
, and city
. However, since all of these values are scalars (i.e., single values), pandas is unable to infer the index for the DataFrame and raises a ValueError
.
To fix this, you can pass an explicit index to the DataFrame constructor, like this:
import pandas as pd
name = 'John'
age = 30
city = 'New York'
df = pd.DataFrame({'Name': name, 'Age': age, 'City': city}, index=[0])
print(df)
Or you can pass the values in a list or numpy array and with the key of the dataframe you will be able to fix the issue
df = pd.DataFrame({'Name': [name], 'Age': [age], 'City': [city]})