I have below code
I am trying to insert new columns as specific positions with insert
method. Below is my code,
import pandas as pd
(pd.DataFrame({'product name': ['laptop', 'printer', 'printer',], 'price': [1200, 150, 1200], 'price1': [1200, 150, 1200]})
.insert(0, 'AAA', -1)
.insert(1, 'BBB', -2)
)
With this I am getting below error,
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'insert'
>>>
Could you please help to resolve this error.
Any pointer is highly appreciated.
CodePudding user response:
Cause of the error
DataFrame.insert
is the inplace operation which modifies the original dataframe and returns None
. After calling the first insert
operation the return value is None
hence the next insert
throws an error complaining that 'NoneType' object has no attribute 'insert'
.
Solution
df = pd.DataFrame({'product name': ['laptop', 'printer', 'printer',], 'price': [1200, 150, 1200], 'price1': [1200, 150, 1200]})
df.insert(0, 'AAA', -1)
df.insert(1, 'BBB', -2)
Hacky solution
df.pipe(lambda x: x.insert(0, 'AAA', -1) or x.insert(1, 'BBB', -2) or x)
CodePudding user response:
The insert method doesn't return a dataframe object. You can assign the dataframe object to a variable and apply the insert method to the variable:
df = pd.DataFrame({'product name': ['laptop', 'printer', 'printer',],
'price': [1200, 150, 1200],
'price1': [1200, 150, 1200]})
df.insert(0, 'AAA', -1)
df.insert(1, 'BBB', -2)
You can also use join to have it within the chain, but you have to know the number of rows:
pd.DataFrame({'AAA': [-1] * 3})\
.join(pd.DataFrame({'BBB': [-2] * 3}))\
.join(pd.DataFrame({'product name': ['laptop', 'printer', 'printer', ],
'price': [1200, 150, 1200],
'price1': [1200, 150, 1200]}))