3

I have a simple txt file and I am reading it as follows:

data=pd.read_csv("data1.txt",sep=',', header = None)
data.columns=['X1', 'Y']

when I print this I get:-

       X1        Y
0      6.1101  17.5920
1      5.5277   9.1302
2      8.5186  13.6620
3      7.0032  11.8540
4      5.8598   6.8233

Now I want to insert a Column X0 in front of X1 ( to its left) and give this column a value of 1.so I added this code:-

data = data.insert(0,'X0',1)    
print(type(data))
print(len(data))

But I get the following error message:-

<class 'NoneType'>
TypeError: object of type 'NoneType' has no len()

The question is , is my data.insert correct?. why is that type of the dataframe coming as NoneType. what am I doing wrong here?.

2 Answers 2

3

Instead of using insert which acts in place, you can use assign

data = data.assign(X0=1)[['X0'] + data.columns.tolist()]
print(data)

   X0      X1        Y
0   1  6.1101  17.5920
1   1  5.5277   9.1302
2   1  8.5186  13.6620
3   1  7.0032  11.8540
4   1  5.8598   6.8233
Sign up to request clarification or add additional context in comments.

Comments

3

You cannot assign DataFrame.insert to new DataFrame, because it works inplace:

data.insert(0,'X0',1) 
print (data)
   X0      X1        Y
0   1  6.1101  17.5920
1   1  5.5277   9.1302
2   1  8.5186  13.6620
3   1  7.0032  11.8540
4   1  5.8598   6.8233

3 Comments

Thank you. Yes it worked. I am still an entry level with Pandas. appreciate your help.
I wish the doc had explicitly mentioned it.
Yes, I was surprised too - also I check it in docs here - In [67]:

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.