1
$\begingroup$

I am new in using python for data science.
What is the difference between selecting a a column with: df['name'].values and df.iloc[:,1].values and df.iloc[:,1:2].values they return differnt types of numpy vectors. why?

$\endgroup$
  • 3
    $\begingroup$ assuming 'name' is the second column. they should be identical. please includes some example codes, so we can help you. $\endgroup$ – Louis T Feb 10 at 2:03
1
$\begingroup$

Not entirely sure what you mean by "numpy vectors" but am assuming the question is why each of these methods return essentially (almost but not quite) the same output...

Reference: pandas docs: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

df['name'].values is a "Series corresponding to colname". In other words, you're just calling the data from that column and putting the in an array by calling .values.

.iloc is a "Purely integer-location based indexing for selection by position". Same as above but you're calling the indexed location of the column where df.iloc[:, 1] is df.iloc[all rows, col 2]. Probably an easier method to call multiple consecutive columns in a DataFrame then writing out each individual column name.

df.iloc[:,1:2].values <-- creates an array of arrays where the main array is the column that you called (col2) and each row values is contained in a subarray. This is--I think-- because you're slicing the dataframe between column index locations 1 and 2 (rather than just calling loc 1 like above). This would mean that each row is being called individually so that a new array is created for each row that exists between column index locations 1 and 2 (which is the 'parent' array).

$\endgroup$
-1
$\begingroup$

Assuming 'name' is the second column. they should be identical. Pandas use the 0-based index. So the first element is index 0. That might the 'gotcha' bit here.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.