3 回答

TA贡献1805条经验 获得超9个赞
用 -
def dict_op(x):
string1 = x['column1']
string2 = x['column2']
start_pos = x['start']
x['val'] = {i: i + start_pos for i, _ in enumerate(string1)}
return x
def zip_dict(x):
b=pd.DataFrame(x)
return {i:b.loc[:,i].tolist() for i in b.columns }
op = df.apply(dict_op, axis=1).groupby('column1')['val'].apply(list).apply(zip_dict)
print(op)
输出
column1
LJNVTJOY {0: [31, 52, 84], 1: [32, 53, 85], 2: [33, 54,...
MXRBMVQDHF {0: [79], 1: [80], 2: [81], 3: [82], 4: [83], ...
WHLAOECVQR {0: [18], 1: [19], 2: [20], 3: [21], 4: [22], ...
Name: val, dtype: object
解释
该dict_op重用你的代码创建的每一行的字典,然后.apply(list)将拉链类型的字典在一起,形成类型的字典列表。
在zip_dict()随后创建输出dict了临时的输出。
我没有包含的最后一部分是如果列表的长度为 1 那么你可以只包含第一个元素的部分,将输出从{0: [79], 1: [80], 2: [81], 3: [82], 4: [83], ...到{0: 79, 1: 80, 2: 81, 3: 82, 4: 83, ...

TA贡献1829条经验 获得超9个赞
首先应用 groupby 函数将“开始”列聚合为列表
df2 = df.groupby("column1")["start"].apply(list).reset_index()
现在,您可以编写一个函数来创建新的字典列
def create_dict(row):
new_dict = {}
for i, j in enumerate(row["column1"]):
if len(row["start"]) == 1:
new_dict[i] = row["start"][0]+i
else:
for k in row["start"]:
if i in new_dict:
new_dict[i].append(k + i)
else:
new_dict[i] = [k + i]
return new_dict
最后,将此函数应用于 df2 的所有行
df2["new_column"] = df2.apply(create_dict, axis = 1)

TA贡献1811条经验 获得超6个赞
这是使用 alambda和 two的略有不同的方法zips。
df2 = df.groupby('column1')['start'].agg([('s', list)]).reset_index()
df2['l'] = df.column1.str.len()
df2.apply(lambda x: dict(zip(range(x['l'] + 1), zip(*[range(s, s + x['l'] + 1) for s in x['s']]))), axis = 1)
可以在此处看到截断的输出(请注意,它返回元组而不是列表):
0 {0: (31, 52, 84), 1: (32, 53, 85), 2: (33, 54,...
1 {0: (79,), 1: (80,), 2: (81,), 3: (82,), 4: (8...
2 {0: (18,), 1: (19,), 2: (20,), 3: (21,), 4: (2...
首先,为了减少apply步骤的长度,创建一个包含column1值和相关起始位置的 DataFrame 。另外,添加一个长度为column1(假设等长断言成立)的列。
之后,就是组合column1字母索引的范围(0通过len(column1),用作键,以及由start值偏移的相同范围)。
第二个事情变得有点冒险,zip因为[range(s, s + x['l'] + 1) for s in x['s']]返回看起来像这样的东西(对于'LJNVTJOY'):
[[31, 32, 33, 34, 35, 36, 37, 38, 39],
[52, 53, 54, 55, 56, 57, 58, 59, 60],
[84, 85, 86, 87, 88, 89, 90, 91, 92]]
当我们真的想对垂直对齐的元素进行分组时,我们使用“splat”或“ unpacking ”运算符将这些列表输入到zip. 一旦我们组合了这些列表,我们就有了一个键列表和一个值列表(元组),它们可以zipped放入dict.
添加回答
举报