gpt4 book ai didi

python - 比较数据框中的两列python

转载 作者:行者123 更新时间:2023-11-30 22:24:07 24 4
gpt4 key购买 nike

我正在尝试比较数据框中的一行是否为某个值。

例如: if word = 'bleu' and ink = 'blue' ,我想在我的数据框中添加一个新列 'congruent' = 1if not = 0 .

我写了这段代码:

import pandas as pd
import numpy as np
import random

word = ['bleu', 'rouge', 'vert', 'jaune']

ink = ['blue', 'red', 'green', 'yellow']

my_list_word = [random.choice(word) for _ in range(60)]

df = pd.DataFrame(my_list_word, columns=["word"])

my_list_ink = [random.choice(ink) for _ in range(60)]

df['ink'] = my_list_ink

df['congruent'] = 0

print(df)

我尝试做一个循环,但没有成功,我的全等列全为 0。

有人知道怎么做吗?

谢谢!

最佳答案

我认为您正在寻找映射和匹配,即

di = dict(zip(word,ink))
df['new'] = (df['word'].map(di) == df['ink']).astype(int)

word ink new
0 bleu red 0
1 jaune yellow 1
2 jaune blue 0
3 jaune yellow 1
4 vert blue 0

关于python - 比较数据框中的两列python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908340/

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