Skip to main content
 首页 » 编程设计

python之使用 Pandas 数据框列中的整数从另一列内的列表中提取特定值

2025年02月15日9softidea

我有一个数据框,其中一列包含一个列表,另一列包含该行的特定整数值。我想使用此整数值从另一列内的列表中提取特定值:

df:

    list                                         val 
1   ['mohamed', 'adam', 'paul', 'dave']           3 
2   ['dave', 'fred']                              0 
3   ['john', 'dave', 'jane']                      1 
4   ['dave']                                      0 

创建者:

df = df.loc[df['unsplit_list'].str.contains('dave')] 
df['list'] = df['unsplit_list'].str.split('|') 
df['val'] = df['list'].apply(lambda lst: [i for i, x in enumerate(lst) if 'dave' in x][0]) 
df['val'] = df['val'].astype(int) 

当我尝试从我的列表中获取 dave 的值时,出现错误:

df['list'].str[df['val']] 
 
>> 
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

但是如果我这样做了:

df['list'].str[df[1]] 

然后我就可以使用这个整数获得列表中的值。我怎样才能得到我想要的这个值?

请您参考如下方法:

df['name'] = [row[0][row[1]] for ix, row in df.iterrows()]