March 15, 2023, 5:34pm
Stack Overflow there is code such as
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(10, size=(3,1)), columns=['A'])
df = df.reindex(columns=[*df.columns.tolist(), 'col1', 'col2'], fill_value=0)
What is the meaning of
* in the 4th line? Thanks.
* unpacks a list. So if
my_list = ["cat", "dog", "bird"] then
*my_list would evaluate to
"cat", "dog", "bird".
In the code you provided
df.columns.tolist() returns a list, then the items are unpacked, extended with the additional items ‘col1’ and ‘col2’, and then all put into a new list (inside the square brackets).
March 15, 2023, 5:49pm
This is iterable unpacking:
>>> [*range(5,0,-1), "blast-off"]
[5, 4, 3, 2, 1, 'blast-off']
this could have also been achieved by using
March 16, 2023, 12:03am
None because it is a method
modifying an object in place (modifies the list). That makes it hard to
embed concisely in an expression as in the OP’s example.
df.columns.tolist() + ['col1', 'col2'] though.
Cameron Simpson firstname.lastname@example.org
You’re right. I can’t tell you how many times this bites me, in-place list methods return None. Grrrr.
March 16, 2023, 2:39am
Better to be bitten than to have lurking bugs from mistakenly modified objects IMO.