如何在pandas表中只在一次迭代中设置多个值?

2024-06-20 15:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用itertuples()迭代器函数迭代pandas表。当条件为真时,我想在另一列中设置一个值。这很简单。但是我想在之前设置的值的基础上再设置另一个值到另一列,这不起作用。我不得不再安排一次这样做,但这是低效的。 如何在一个迭代过程中在不同的列中设置多个值。在

下面是一些示例代码:

data = {
'Animal': ['cat', 'dog', 'dog', 'cat', 'bird', 'dog', 'cow'],
'Noise': ['muh', 'miau', 'wuff', 'piep', 'piep', 'miau', 'muh']
}

df = pd.DataFrame(data)
df.insert(loc=2, column='Match', value='')
df.insert(loc=3, column='Comment', value='')
for row in df.itertuples():
    if row.Animal == 'cat' and row.Noise == 'miau':
        df.set_value(index=row.Index, col='Match', value=True)
    elif row.Animal == 'dog' and row.Noise == 'wuff':
        df.set_value(index=row.Index, col='Match', value=True)
    elif row.Animal == 'bird' and row.Noise == 'piep':
        df.set_value(index=row.Index, col='Match', value=True)
    elif row.Animal == 'cow' and row.Noise == 'muh':
        df.set_value(index=row.Index, col='Match', value=True)

    # Why is this not getting applied to the 'Comment' column?
    if row.Match is True:
        df.set_value(index=row.Index, col='Comment', value='yeah')

我必须进行另一次迭代来填充注释列:

^{pr2}$

但是对于500000+的值,这是非常低效和耗时的。 那么,有什么更好的方法来做这样的事情呢?在


Tags: andtruedfindexvaluematchcolcat
2条回答

考虑您的df

data = {
'Animal': ['cat', 'dog', 'dog', 'cat', 'bird', 'dog', 'cow'],
'Noise': ['muh', 'miau', 'wuff', 'piep', 'piep', 'miau', 'muh']
}

df = pd.DataFrame(data)

我会用一个最初计算过的字典来定义什么是匹配。然后,使用map转换并测试是否相等。之后,我将使用assign生成所需的列。在

^{pr2}$

回答您的具体问题:
循环中的row不再附加到数据帧。因此,当您使用TrueFalse分配给数据帧时,您将无法访问刚刚从row设置的值。相反,请使用df.get_value

for row in df.itertuples():
    if row.Animal == 'cat' and row.Noise == 'miau':
        df.set_value(index=row.Index, col='Match', value=True)
    elif row.Animal == 'dog' and row.Noise == 'wuff':
        df.set_value(index=row.Index, col='Match', value=True)
    elif row.Animal == 'bird' and row.Noise == 'piep':
        df.set_value(index=row.Index, col='Match', value=True)
    elif row.Animal == 'cow' and row.Noise == 'muh':
        df.set_value(index=row.Index, col='Match', value=True)

    # This should work
    if df.get_value(index=row.Index, col='Match') is True:
        df.set_value(index=row.Index, col='Comment', value='yeah')

而不是

 # Why is this not getting applied to the 'Comment' column?
    if row.Match is True:
        df.set_value(index=row.Index, col='Comment', value='yeah')

你可以在for循环之后使用这个。在

^{pr2}$

相关问题 更多 >