gpt4 book ai didi

python - 填充源 - 目标对和列表中的标志

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:53 31 4
gpt4 key购买 nike

我有一个列表,它有一个源到目标流,看起来像 -

path_list = ['A', 'A', 'B', 'C', 'C']

我想为上面的列表填充一个 DataFrame,它有 3 列 -
源、目标、标志。示例 -

source destination flag
'A' 'A' Type_1
'A' 'B' -
'B' 'C' -
'C' 'C' Type_2

我想根据规则填充 flag 列 - 如果 list 中的前 2 个条目相同,则 Type_1 并且如果最后 2 个条目与 Type_2 相同。所有其他源-目标对将被标记为 -

我已经完成了一半,并且有一个脚本可以填充 sourcedestination 列 -

pd.DataFrame({'source': path_list[:-1], 'destination': path_list[1:]})

如何添加标志列并填充它?

最佳答案

给特定的单元格值使用df.flag.iat[0]

import pandas as pd

path_list = ['A', 'A', 'B', 'C', 'C']
df = pd.DataFrame({'source': path_list[:-1], 'destination': path_list[1:]})
df['flag'] = '-'

if path_list[0] == path_list[1]:
df.flag.iat[0] = 'Type_1'

if path_list[-1] == path_list[-2]:
df.flag.iat[-1] = 'Type_2'
print(df)

输出:

  source destination   flag
0 A A Type_1
1 A B -
2 B C -
3 C C Type_2

关于python - 填充源 - 目标对和列表中的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54529485/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com