[英]I want to split on a comma in a column where the values are seperated by commas
我有一個數據框,看起來像:
data = {'X':['A, B, C'], 'Y':[['apple, pear, berries'], ['milk, butter, eggs'], ['apple, milk, bread']]}
data = pd.DataFrame(data)
我正在嘗試遍歷“ Y”列以拆分“,”並保存到僅存儲唯一值的空列表中。
我努力了:
list = data['Y'].tolist()
new_list = set(list)
但是它不返回我想要的東西。
任何幫助將非常感激。
預期的輸出看起來像一個出現的列表:
['apple', 'pear', 'berries', 'milk', 'butter', 'eggs', 'bread']
嘗試以下單行代碼,不使用Pandas:
data = {'X':['A', 'B', 'C'], 'Y':[['apple', 'pear', 'berries'], ['milk', 'butter', 'eggs'], ['apple', 'milk', 'bread']]}
list(set(sum(data['Y'], [])))
# output: ['apple', 'milk', 'bread', 'pear', 'eggs', 'butter', 'berries']
您可以將我的解決方案與基於熊貓的解決方案進行比較:
%%timeit
list(set(sum(data['Y'], [])))
# 805 ns ± 4.84 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
# Without df creation
%%timeit
#df = pd.DataFrame(data)
l = df['Y'].values.tolist() # this will have the same as data['Y']
new_list = list(set(reduce(lambda x,y: x+y,l)))
# 5.75 µs ± 220 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# With df creation
%%timeit
df = pd.DataFrame(data)
l = df['Y'].values.tolist() # this will have the same as data['Y']
new_list = list(set(reduce(lambda x,y: x+y,l)))
# 658 µs ± 23.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
從前面的結果可以看出,我的解決方案似乎比基於熊貓的解決方案更有效。 簡單更好 :-)
您的邏輯可能存在缺陷。 首先,不要使用list
作為變量名,因為這是Python的內置函數。
其次,我認為您不清楚data
是否是字典,因此data['Y']
將為您提供列表列表。 因此,您將無法應用與數據框一起使用的方法。
第三,您可以使用reduce
函數獲得預期的輸出
我相信您希望將data
轉換為數據框,因此請使用以下命令:
import pandas as pd
from functools import reduce
data = {'X':['A', 'B', 'C'], 'Y':[['apple', 'pear', 'berries'], ['milk', 'butter', 'eggs'], ['apple', 'milk', 'bread']]}
df = pd.DataFrame(data)
l = df['Y'].values.tolist() # this will have the same as data['Y']
new_list = list(set(reduce(lambda x,y: x+y,l)))
您可以節省一些時間,方法是不轉換為數據幀,而是將reduce函數直接應用於data['Y']
:
new_list = list(set(reduce(lambda x,y: x+y, data['Y'])))
輸出量
['apple', 'berries', 'bread', 'butter', 'eggs', 'milk', 'pear']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.