我正在尝试分离一个具有这样值的 Pandas 数据框列 -
我的目标是为每个“约束”创建一个值列表,并将每个值放在单引号内。这应该是预期的输出 -
我已经尝试过 pandas groupby apply(list) 但它没有按预期工作。我希望得到一个合适的熊猫列表,其中每个值都在引号内,然后用逗号分隔,但是,它生成以下输出(值用逗号分隔,但引号仅在第一个值之前和最后一个值之后)。
这是我的代码 -
grouped_targets = target_table.groupby(['user_id', 'target_type'])['constraints'].apply(set).apply(list).reset_index()
grouped_targets.head()
这是我的代码生成的输出-
我做错了什么?
答案 0 :(得分:1)
在扁平嵌套列表的列表理解中使用自定义 lambda 函数按 ,
拆分值,转换为集合并最后到列表:
target_table = pd.DataFrame({'user_id':[1,2,1,2,1,2],
'target_type':[2,8,2,8,8,8],
'constraints':['aaa, dd','ss, op','ja, ss',
'dd, su, per', 'a', 'uu, ss']})
f = lambda x: list(set(["'" + z + "'" for y in x.str.split(', ') for z in y]))
grouped_targets = (target_table.groupby(['user_id', 'target_type'])['constraints']
.apply(f)
.reset_index())
print (grouped_targets['constraints'].tolist())
[["'ss'", "'aaa'", "'dd'", "'ja'"], ["'a'"],
["'ss'", "'per'", "'uu'", "'su'", "'op'", "'dd'"]]
f = lambda x: list(set([z for y in x.str.split(', ') for z in y]))
grouped_targets = (target_table.groupby(['user_id', 'target_type'])['constraints']
.apply(f)
.reset_index())
print (grouped_targets['constraints'].tolist())
[['ss', 'dd', 'aaa', 'ja'], ['a'],
['ss', 'su', 'uu', 'per', 'op', 'dd']]
编辑:
我认为最复杂的是自定义函数,你可以在列表中测试它是如何工作的:
L = ['aaa, dd','ss, op','ja, ss', 'dd, su, per', 'a', 'uu, ss']
如果只有列表输出中的拆分值不同,则获取列表列表(嵌套列表):
a = [x.split(', ') for x in L]
print (a)
[['aaa', 'dd'], ['ss', 'op'], ['ja', 'ss'], ['dd', 'su', 'per'], ['a'], ['uu', 'ss']]
flatten values 与 split
结合使用也是可能的:
a = [z for x in L for z in x.split(', ')]
print (a)
['aaa', 'dd', 'ss', 'op', 'ja', 'ss', 'dd', 'su', 'per', 'a', 'uu', 'ss']
答案 1 :(得分:0)
您应该能够通过拆分字符串来实现这一点,因此:
new_df = df['constraints'].apply(lambda x: x.split(', '))
答案 2 :(得分:0)
先尝试使用拆分。
...].str.split(',').apply(list)