【问题标题】:Pandas dataframe: changing values in a column based on conditions in other columns [duplicate]Pandas数据框:根据其他列中的条件更改列中的值[重复]
【发布时间】:2020-09-02 19:45:46
【问题描述】:

我在 pandas 数据框中有一个大型面板数据。示例数据可以在here找到:

import pandas as pd 

df = pd.read_csv('example_data.csv')

df.head()

ID  Year    y   DOB Year_of_death   event
223725  1991    6   1975.0  2021    No
223725  1992    6   1975.0  2021    No
223725  1993    6   1975.0  2021    No
223725  1994    6   1975.0  2021    No
223725  1995    6   1975.0  2021    No

我想更改event 列中的值,以便如果 Year 值对应于Year_of_death 值,然后event 中针对该特定行的观察值或ID 更改为Yes,否则保持为No

例如,ID 68084329 于 2012 年去世,但在 event 列中的每个观察值中都有值 Yes。我想更改它,以便只有 Year 2012 为这个ID 的行在event 中具有Yes。其他 event 值应保持为 No

df.loc[df['ID'] == '68084329']

ID         Year    y    DOB  Year_of_death  event
68084329    1991    6   1942.0  2012    Yes
68084329    1992    5   1942.0  2012    Yes
68084329    1993    5   1942.0  2012    Yes
68084329    1994    6   1942.0  2012    Yes
68084329    1995    6   1942.0  2012    Yes
68084329    1996    5   1942.0  2012    Yes
68084329    1997    6   1942.0  2012    Yes
68084329    1998    5   1942.0  2012    Yes
68084329    1999    6   1942.0  2012    Yes
68084329    2000    6   1942.0  2012    Yes
68084329    2001    6   1942.0  2012    Yes
68084329    2002    5   1942.0  2012    Yes
68084329    2003    6   1942.0  2012    Yes
68084329    2004    5   1942.0  2012    Yes
68084329    2005    5   1942.0  2012    Yes
68084329    2006    6   1942.0  2012    Yes
68084329    2007    6   1942.0  2012    Yes
68084329    2008    6   1942.0  2012    Yes
68084329    2010    5   1942.0  2012    Yes
68084329    2011    5   1942.0  2012    Yes
68084329    2012    0   1942.0  2012    Yes

对于ID多的大型DataFrame,如何按照上述条件进行这些更改?

【问题讨论】:

  • 不确定 ID 在这里的重要性,所以我认为 df['event'] = np.where(df['Year'].eq(df['Year_of_death']), 'Yes','No') 会这样做
  • 在这里工作得很好,非常感谢您的帮助
  • 这能回答你的问题吗? Compare two columns using pandas
  • @Ben.T 我觉得这是 SO 中最好的功能,请其他人帮助您找到正确的搜索词

标签: python pandas dataframe


【解决方案1】:
df.loc[df[Year'] == df['Year of Death'], 'Event'] = 'Yes'

这在我正在编写的一段类似的代码中起作用。

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 2022-07-28
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多