Python Pandas selecting element in array column

0 votes
I have the following data frame:

pa=pd.DataFrame({'a':np.array([[1.,4.],[2.],[3.,4.,5.]])})
 

Now what should I do if I want to select the column 'a' and then only a particular element (i.e. first: 1., 2., 3.)

What do I need to add to the following:

pa.loc[:,['a']]
 

Can anyone provide the solution?
May 13, 2019 in Python by ana1504.k
• 7,910 points
4,440 views

1 answer to this question.

0 votes
pa.loc[row] selects the row with label row.

pa.loc[row, col] selects the cells which are the instersection of row and col

pa.loc[:, col] selects all rows and the column named col. Note that although this works it is not the idiomatic way to refer to a column of a dataframe. For that you should use pa['a']

Now you have lists in the cells of your column so you can use the vectorized string methods to access the elements of those lists like so.

pa['a'].str[0] #first value in lists
pa['a'].str[-1] #last value in lists
answered May 13, 2019 by SDeb
• 13,290 points

Related Questions In Python

0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,780 points
663 views
0 votes
1 answer

Delete column from pandas DataFrame in python

As you've guessed, the right syntax is del ...READ MORE

answered Dec 19, 2020 in Python by Gitika
• 65,910 points
73 views
0 votes
1 answer

Adding new column to existing DataFrame in Python pandas

Use the original df1 indexes to create ...READ MORE

answered Dec 23, 2020 in Python by Gitika
• 65,910 points
110 views
+4 votes
7 answers
0 votes
1 answer

Numpy: Multiplying large arrays with dtype=int8 is SLOW

Unfortunately, as correctly underlined in the comments, the ...READ MORE

answered Sep 5, 2018 in Python by Priyaj
• 58,120 points
993 views
0 votes
1 answer

Python: Issue with 'unexpected end of pattern'

I should start by stating that using ...READ MORE

answered Sep 12, 2018 in Python by Priyaj
• 58,120 points
829 views
0 votes
1 answer

Python: Issue with 'unexpected end of pattern'

I should start by stating that using ...READ MORE

answered Sep 24, 2018 in Python by Priyaj
• 58,120 points
714 views
0 votes
1 answer

How to create Pandas series from numpy array?

Hi. Refer to the below command: import pandas ...READ MORE

answered Apr 1, 2019 in Python by Pavan
1,783 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 13,290 points
269 views
0 votes
1 answer

Array values in Python

You can use the enumerate function and ...READ MORE

answered Nov 28, 2018 in Python by SDeb
• 13,290 points
99 views