Python 创建数据帧、列表列、创建累积列表集列和逐记录差异
我有一个简单的数据框Python 创建数据帧、列表列、创建累积列表集列和逐记录差异,python,list,pandas,lambda,set,Python,List,Pandas,Lambda,Set,我有一个简单的数据框df,其中有一列列表lists。我想根据列表生成3个附加列 df看起来像: import pandas as pd lists={1:[[1]],2:[[1,2,3]],3:[[2,9,7,9]],4:[[2,7,3,5]]} #create test dataframe df=pd.DataFrame.from_dict(lists,orient='index') df=df.rename(columns={0:'lists'}) df lists 1
df
,其中有一列列表lists
。我想根据列表
生成3个附加列
df
看起来像:
import pandas as pd
lists={1:[[1]],2:[[1,2,3]],3:[[2,9,7,9]],4:[[2,7,3,5]]}
#create test dataframe
df=pd.DataFrame.from_dict(lists,orient='index')
df=df.rename(columns={0:'lists'})
df
lists
1 [1]
2 [1, 2, 3]
3 [2, 9, 7, 9]
4 [2, 7, 3, 5]
我希望df
看起来像这样:
lists cumset adds drops
1 [1] {1} {1} {}
2 [1,2,3] {1,2,3} {2,3} {}
3 [2,9,7,9] {1,2,3,7,9} {7,9} {3}
4 [2,7,3,5] {1,2,3,5,7,9} {3,5} {9}
基本上,我需要弄清楚如何创建cumset
(某种类型的apply?,(是否已经有pandas函数?)。然后对于添加和删除,基本上我们要比较df.list和df.list.shift(),并确定哪些项是新的,哪些项缺少。可能类似于:
df['adds']=df[['lists',df.lists.shift()]].apply(lambda x: {i for i in x.lists if i not in x.lists.shift()}, axis=1)
祝您玩得开心,谢谢。您可以使用创建累积列,使用集合而不是列表创建列,并使用创建“添加”和“删除”列:
我认为您可以使用++并主要用于set
s:
df['cumset'] = df['lists'].cumsum().apply(set)
lists_sets = df['lists'].apply(set)
lists_shifted = lists_sets.shift()
#replace first value - NaN to set
lists_shifted.iat[0] = set()
lists_shifted = lists_shifted.apply(set)
df['add'] = lists_sets - lists_shifted
df['drop'] = lists_shifted - lists_sets
print (df)
lists cumset add drop
1 [1] {1} {1} {}
2 [1, 2, 3] {1, 2, 3} {2, 3} {}
3 [2, 9, 7, 9] {1, 2, 3, 9, 7} {9, 7} {1, 3}
4 [2, 7, 3, 5] {1, 2, 3, 5, 7, 9} {3, 5} {9}
非常好,它很有效。我认为最好的解决方案是下面的lukess和@jezreal的组合。IMO lukess处理['add']和['drop']的pythonic比使用实际的df列创建新的temp列的实例稍微多一些。jezreal处理的pythonic稍微多一些。cumsum不需要np.unique,并应用(set)与使用lambda不同。lukess使用“else set”修复从shift创建的nan稍微好一点,而不是专门应用于0索引。很棒的工作伙伴。选择lukess是因为他是第一个,但两人都获得了投票权!thx jezreal。请参阅所选解决方案中lukess中的注释。不过,您的方法非常有效,我也获得了投票权。
df['cumset'] = df['lists'].cumsum().apply(set)
lists_sets = df['lists'].apply(set)
lists_shifted = lists_sets.shift()
#replace first value - NaN to set
lists_shifted.iat[0] = set()
lists_shifted = lists_shifted.apply(set)
df['add'] = lists_sets - lists_shifted
df['drop'] = lists_shifted - lists_sets
print (df)
lists cumset add drop
1 [1] {1} {1} {}
2 [1, 2, 3] {1, 2, 3} {2, 3} {}
3 [2, 9, 7, 9] {1, 2, 3, 9, 7} {9, 7} {1, 3}
4 [2, 7, 3, 5] {1, 2, 3, 5, 7, 9} {3, 5} {9}