Skip to main content
 首页 » 编程设计

python之从 Pandas 数据框文本列获取数组的有效方法

2024年11月01日6三少

我可以使用 df.col.apply(lambda x ... 之类的结构,而不使用“传统的”for 循环(遍历列和另一个迭代每列的字符串值中的单词)?

我所有的尝试都给出了类似The truth value of an array with more than one elements is ambiguous这样的错误信息。使用 a.any() 或 a.all()。

例子:

d = {'foo' : [1,2,3], 'bar': [-2,-2,-3]} 
df = pd.DataFrame({'col': ['foo mur bar','foo','mur mur']}, index=[1,2,3]) 

预期输出是:

np.array([ 
    [[1,2,3],[-2,-2,-3]], 
    [[1,2,3]], 
    [[]] 
]) 

请您参考如下方法:

尝试使用:

a = df['col'].str.split().apply(lambda x: pd.Series(x).map(d)).values 
a = np.array([pd.Series(i).dropna().values for i in a]) 
print(a) 

输出:

[array([[1, 2, 3], [-2, -2, -3]], dtype=object) 
 array([[1, 2, 3]], dtype=object) array([], dtype=object)]