0

How would I be able to print the last value of element_val numpy arrays. It is the second index of [ 2. 2. 30.] which is 30. So the values will go like 30,40,50...670,680. How would I be able to do that since the numpy array is 1 dimensional?

input.csv file:

element,LNPT,SNPT,NLP,NSP,TNT,TPnL,MxPnL,MnPnL,MxU,MxD
[ 2.  2. 30.],0,0,4,4,8,-0.1,-0.0,-0.1,17127,-3
[ 2.  2. 40.],0,0,2,2,4,0.0,-0.0,-0.0,17141,-3
[ 2.  2. 50.],0,0,2,2,4,0.0,-0.0,-0.0,17139,-3
[ 2.  2. 60.],2,0,6,6,12,0.5,2.3,-1.9,17015,-3
[ 2.  2. 70.],1,0,4,4,8,0.3,0.3,-0.0,17011,-3

Code:

import numpy as np
import pandas as pd

my_data = pd.read_csv('input.csv').to_numpy()
element_vals = my_data[:,0]
print(element_vals)

Output:

['[ 2.  2. 30.]' '[ 2.  2. 40.]' '[ 2.  2. 50.]' ... '[  6.    7.5 660. ]'
 '[  6.    7.5 670. ]' '[  6.    7.5 680. ]']
10
  • That output looks like you printed an array to a file, rather than actually writing CSV, then tried to read the file as CSV anyway. Commented Apr 15, 2021 at 21:30
  • print should never be used as a way of saving NumPy array data. It discards data by default, and it's awkward to parse even when it doesn't discard data. Use numpy.save and numpy.load, or numpy.savetxt and numpy.loadtxt. Commented Apr 15, 2021 at 21:33
  • (Actually, considering details like the spacing and lack of extra brackets, it looks like you probably printed a number of arrays individually, possibly printing each row of a 2D array. Either way, it's a bad idea, and pandas.read_csv is the wrong tool to read this.) Commented Apr 15, 2021 at 21:41
  • Plus, element_vals has probably lost the first data row, since read_csv probably interpreted it as a column header. Commented Apr 15, 2021 at 21:42
  • If I read it directly from numpy it would give me an error and the [ 2. 2. 30.] values get outputted as nan when I use genfromtxt hence why I used pandas. I have updated to show what the issue to show what input.csv looks like. Commented Apr 15, 2021 at 22:24

1 Answer 1

1

Use str.strip(), str.split(), and to_numpy() to manually convert the df.element column into a real numpy array:

df = pd.read_csv('input.csv')
element_vals = df.element.str.strip('[]').str.split(expand=True).astype(float).to_numpy()

# array([[ 2.,  2., 30.],
#        [ 2.,  2., 40.],
#        [ 2.,  2., 50.],
#        [ 2.,  2., 60.],
#        [ 2.,  2., 70.]])

Then you can index as expected:

element_vals[:, 2]

# array([30., 40., 50., 60., 70.])
Sign up to request clarification or add additional context in comments.

Comments

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.