gpt4 book ai didi

python - 遍历一列列表并根据列表顺序附加其他列

转载 作者:行者123 更新时间:2023-12-01 23:29:58 24 4
gpt4 key购买 nike

cats = {'lesson_name': {0: 'Mutt',
1: 'Ragdoll',
2: 'Black',
3: 'Calico',
4: 'Tortoise',
5: 'Mainecoon'},
'tag_list': {0: ['Orange', 'Black', 'White'],
1: ['Grey', 'White'],
2: ['Black','Brown'],
3: ['Orange','Grey','White'],
4: ['Orange', 'Brown','White'],
5: ['Grey','White']},
'Orange': {0: '',
1: '',
2: '',
3: '',
4: '',
5: ''},
'Black': {0: '',
1: '',
2: '',
3: '',
4: '',
5: ''},
'White': {0: '',
1: '',
2: '',
3: '',
4: '',
5: ''},
'Grey': {0: '',
1: '',
2: '',
3: '',
4: '',
5: ''},
'Brown': {0: '',
1: '',
2: '',
3: '',
4: '',
5: ''}}

cats_frame = pd.DataFrame(cats)

我正在尝试创建一个函数,根据“tag_list”列中列表的顺序附加颜色列(橙色、黑色、白色、灰色、棕色)。例如,如果“橙色”是 tag_list 中的第一种颜色,我希望该行在橙色列中有一个“1”,如果列表中的第二种颜色是“黑色”,我希望该行有一个“黑色列中的 2'。

我正在考虑为每种颜色制作一个函数并尝试过:

def black(df):

for (df['tag_list'],j) in df.iteritems():

if [j][0] == 'Black':
return 1

if [j][1] == 'Black':
return 2

if [j][2] == 'Black':
return 3

else:
return 0

cats_frame['Black'] = cats_frame.apply(black,1)

最佳答案

这是解决问题的一种方法:

tag = pd.DataFrame(cats_frame['tag_list'].tolist())
tag_order = tag.stack().reset_index(level=1)\
.set_index(0, append=True)['level_1'].add(1).unstack(fill_value=0)

cats_frame.update(tag_order)

详细信息:

>>> tag

0 1 2
0 Orange Black White
1 Grey White None
2 Black Brown None
3 Orange Grey White
4 Orange Brown White
5 Grey White None

>> tag_order

0 Black Brown Grey Orange White
0 2 0 0 1 3
1 0 0 1 0 2
2 1 2 0 0 0
3 0 0 2 1 3
4 0 2 0 1 3
5 0 0 1 0 2

>> cats_frame

lesson_name tag_list Orange Black White Grey Brown
0 Mutt [Orange, Black, White] 1 2 3 0 0
1 Ragdoll [Grey, White] 0 0 2 1 0
2 Black [Black, Brown] 0 1 0 0 2
3 Calico [Orange, Grey, White] 1 0 3 2 0
4 Tortoise [Orange, Brown, White] 1 0 3 0 2
5 Mainecoon [Grey, White] 0 0 2 1 0

关于python - 遍历一列列表并根据列表顺序附加其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66444201/

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