Ad

Matrix 0th Row 0th Column Reading "Dog" Instead Of "Target"

- 1 answer

I am trying to append certain strings to a matrix. One that reads "Target" on the 0th row 0th column. And one that reads "Dog" on the 0th column 1st row downwards to the last row of the matrix.

My initial matrix looks like: enter image description here

I have a small issue with the following program:

import numpy as np
import pandas as pd

main=pd.read_csv('C:/Users/Jonas/Desktop/testfile/biggertest.csv', header=None)

target_col = ['dog'] * main.shape[0]
main.insert(loc = 0, column = 'target', value = target_col)

This creates a new matrix that looks like this: enter image description here

Instead of: enter image description here

I'm wondering what I need to change to make this happen?

Cheers.

Ad

Answer

You could simply make the following modification.

import numpy as np
import pandas as pd

main=pd.read_csv('C:/Users/Jonas/Desktop/testfile/biggertest.csv', header=None)

target_col = ['dog'] * main.shape[0]
target_col[0] = 'target'
main.insert(loc = 0, column = -1, value = target_col)

Alternatively,

import numpy as np
import pandas as pd

main=pd.read_csv('C:/Users/Jonas/Desktop/testfile/biggertest.csv', header=None)

main.insert(loc = 0, column = -1, value = 'dog')
main.at[0,-1] = 'target'

If you want the column indices to go from 0 to 4 (instead of -1 to 3), then you can add the following command:

main.rename(columns = lambda x:x+1,inplace=True)

Resulting output from all commands:

        0  1  2  3  4
0  target  5  5  8  9
1     dog  9  0  2  6
2     dog  6  6  4  3
3     dog  3  3  3  3
Ad
source: stackoverflow.com
Ad