Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pandas DataFrame column insert call

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?.

like image 604
sunny Avatar asked Mar 09 '26 23:03

sunny


1 Answers

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
like image 91
piRSquared Avatar answered Mar 11 '26 12:03

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!