python Pandas : adding list of elements in a specific column to find all_elements

标签 python pandas dataframe

假设我有一个像这样使用 pandas.dataframe 的列:

id  available_fruits  
1   ['apple', 'banana']   
1   []
2   ['apple', 'tomato']
1   ['banana']
2   ['kiwi']

我想创建没有重复的 all_available_fruits 列表,它应该是 ['apple', 'banana', 'kiwi', 'tomato']

换句话说,我想在 pandas.dataframe 列中添加列表中的所有元素。我怎样才能做到这一点?

最佳答案

使用numpy.concatenate对于 flatennig,然后是 numpy.unique :

a = np.unique(np.concatenate(df['available_fruits'].values.tolist())).tolist()
print(a)

['apple', 'banana', 'kiwi', 'tomato']

另一种解决方案是通过chain.from_iterable扁平化,通过set获取唯一性,最后转换为list:

from  itertools import chain
a = list(set(chain.from_iterable(df.available_fruits.values.tolist())))
print(a)
['tomato', 'kiwi', 'apple', 'banana']

时间:

df = pd.concat([df]*10000).reset_index(drop=True)
#print (df)

In [62]: %timeit list(set(concat(df.available_fruits.values.tolist())))
100 loops, best of 3: 3.16 ms per loop

In [63]: %timeit np.unique(np.concatenate(df['available_fruits'].values.tolist())).tolist()
10 loops, best of 3: 99.2 ms per loop

#John Galt's solution
In [64]: %timeit list(set(df.available_fruits.sum()))
1 loop, best of 3: 4.12 s per loop

#pir's solution 0
In [65]: %timeit list(set(concat(df.available_fruits.values.tolist())))
100 loops, best of 3: 3.16 ms per loop

#pir's solution 1
In [66]: %timeit list({k: 1 for x in df.available_fruits.values.tolist() for k in x})
100 loops, best of 3: 4.59 ms per loop

#pir's solution 2
In [67]: %%timeit
    ...: from sklearn.preprocessing import MultiLabelBinarizer
    ...: 
    ...: mlb = MultiLabelBinarizer()
    ...: mlb.fit(df.available_fruits)
    ...: list(mlb.classes_)
    ...: 
100 loops, best of 3: 4.07 ms per loop

#perigon's solution
In [68]: %timeit list(set([val for lst in df.available_fruits for val in lst]))
100 loops, best of 3: 5.1 ms per loop

关于 python Pandas : adding list of elements in a specific column to find all_elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476270/

相关文章:

python - python3 pandas 中的时间轮

python - 根据最近的日期时间比较值

python - 使用 python pandas style.where (或其他方式)为不匹配的两列中的特定单元格着色并导出到 Excel

python - 使用自定义用户模型在 Django 的作者字段中自动添加用户名字

不包括 C++ 标准库头文件的 Python setuptools

python - Pandas 阅读 csv 方向

python - 在 Pandas 中删除特定行

python - 将 Pandas Dataframe 写入 MySQL

python - 在 Django 中流式传输 CSV 文件

python - PySide 关机时出现段错误