1

This is a very basic python question related to adding columns to an existing data frame. Why is it that this

df['Hour'],df['Month'],df['Day'] ="" returns the following error:

ValueError: not enough values to unpack (expected 3, got 0)

but this works fine: df['Hour'],df['Month'],df['Day'] =["","",""]

This seems odd to me, as in my head it appears as though i am assigning a sequence of 3 blank entries to each individual dataframe column, rather than one set of blanks per column.

I'm new to python so I'm sure the answer is obvious, but would someone mind explaining this to me?

2 Answers 2

2

Well, it's hard to give an answer that's not simply "that's because that's how Python syntax is defined". The unpacking you're doing allows you to perform operations like the following:

In [63]: a, b = 3, 5

In [64]: a
Out[64]: 3

In [65]: b
Out[65]: 5

In [66]: l = [8, 10]

In [67]: c, d = l

In [69]: c
Out[69]: 8

In [70]: d
Out[70]: 10

That is, the element on the right hand side is unpacked into the appropriate number of variables on the left hand side. Knowing this, it's clear that you need three elements on the right hand side in your case.

Now what you can do is the following, which perhaps maps more closely to your mental model:

 df['Hour'] = df['Month'] = df['Day'] = ''
Sign up to request clarification or add additional context in comments.

Comments

1

You have multple targets on the left assinment operator.
It's called multiple assingnment. The number of targets on the left operator MUST be equals to number of items on the right:

df['Hour'],df['Month'],df['Day'] = "" # not ok
df['Hour'],df['Month'],df['Day'] = "", "" , "" ok
A, B = 2, 3 # OK 

From grammar

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)
target_list     ::=  target ("," target)* [","]
target          ::=  identifier
                     | "(" [target_list] ")"
                     | "[" [target_list] "]"
                     | attributeref
                     | subscription
                     | slicing
                     | "*" target

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.