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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With