Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing every 1st element of Pandas DataFrame column containing lists

I have a Pandas DataFrame with a column containing lists objects

      A 0   [1,2] 1   [3,4] 2   [8,9]  3   [2,6] 

How can I access the first element of each list and save it into a new column of the DataFrame? To get a result like this:

      A     new_col 0   [1,2]      1 1   [3,4]      3 2   [8,9]      8 3   [2,6]      2 

I know this could be done via iterating over each row, but is there any "pythonic" way?

like image 728
mkoala Avatar asked May 09 '16 20:05

mkoala


People also ask

How do you get the first element in a pandas series?

Accessing the First Element The first element is at the index 0 position. So it is accessed by mentioning the index value in the series. We can use both 0 or the custom index to fetch the value.

How do I get the contents of a column in pandas?

You can get or convert the pandas DataFrame column to list using Series. values. tolist() , since each column in DataFrame is represented as a Series internally, you can use this function after getting a column you wanted to convert as a Series. You can get a column as a Series by using df.

What does First () do in pandas?

Pandas Series: first() function The first() function (convenience method ) is used to subset initial periods of time series data based on a date offset. Keep labels from axis which are in items. in the dataset,and therefore data for 2019-02-13 was not returned.


1 Answers

As always, remember that storing non-scalar objects in frames is generally disfavoured, and should really only be used as a temporary intermediate step.

That said, you can use the .str accessor even though it's not a column of strings:

>>> df = pd.DataFrame({"A": [[1,2],[3,4],[8,9],[2,6]]}) >>> df["new_col"] = df["A"].str[0] >>> df         A  new_col 0  [1, 2]        1 1  [3, 4]        3 2  [8, 9]        8 3  [2, 6]        2 >>> df["new_col"] 0    1 1    3 2    8 3    2 Name: new_col, dtype: int64 
like image 104
DSM Avatar answered Sep 22 '22 06:09

DSM