i have a problem with accessing list element in DataFrame:
import pandas as pd
from pandas import DataFrame
d=DataFrame({'pos': {0: [0.11,0.14,0.46], 1:[1,2,3]},'n': {0: 2.0,1:1}})
Column 'pos' contain a list. I need to calculate new column with 'n'-th element of the list in 'pos'-column In this case: 0.46, 2.
I think it would be smth like this:
d[u'new column']=d.pos.apply(lambda x: x[0])
but instead x[0] i need x[d.n].
I read manual and search the forum but havn't found anything. I fill it smth obvious, but i stucked. Help me, please.
By using at and iat attributes We can also access a single value of a DataFrame with the help of “at” and “iat” attributes. Access a single value by row/column name. At and iat take two arguments. If we pass only one argument, then it will generate an error.
Using Series.tolist() From the dataframe, we select the column “Name” using a [] operator that returns a Series object. Next, we will use the function Series. to_list() provided by the Series class to convert the series object and return a list.
Accessing Element from Series with PositionUse the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.
Conclusion. By using df.at() , df. iat() , df. loc[] method you can insert a list of values into a pandas DataFrame cell.
Thanks to all! This works fine:
def func(x):
return x.pos[int(x.n)]
d['new column']=d.apply(lambda row: func(row), axis=1)
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