Home > Net >  Assigning value to pandas column not working
Assigning value to pandas column not working

Time:03-15

I'm checking if a dataframe is empty and then assigning a value if it is. Dataframe has columns "NAME" and "ROLE"

df = pd.DataFrame(columns = ['NAME', 'ROLE'])

if df.empty:
    df["NAME"] = "Jake"

After assigning "Jake" to "NAME". The dataframe is still empty like so:

NAME ROLE

but I want the dataframe to look like this:

NAME ROLE
Jake

CodePudding user response:

Assigning a scalar to a pandas dataframe sets each value in that column to the scalar. Since you have zero rows, df["NAME"] = "Jake" doesn't assign anything. If you assign a list however, the dataframe is extended for that list. To get a single row in the dataframe

df["NAME"] = ["Jake"]

You could create more rows by adding additional values to the list being assigned.

CodePudding user response:

As people are saying in the comments, there are no rows in your empty dataframe to assign the value "Jake" to the "Name" column. Showing that in the first example:

df = pd.DataFrame(columns=['Name','Role'])
df['Name'] = 'Jake'
print(df)

I'm guessing instead you want to add a row:

df = pd.DataFrame(columns=['Name','Role'])
df = df.append({'Name':'Jake','Role':None},ignore_index=True)
print(df)
  • Related