【问题标题】:Change some values based on condition根据条件更改一些值
【发布时间】:2020-09-24 07:13:51
【问题描述】:

您能帮忙完成以下任务吗?我有一个数据框列,例如:

index df['Q0']
0         1
1         2
2         3
3         5
4         5
5         6
6         7
7         8
8         3
9         2
10        4
11        7

如果 df.loc[0,'Q0'],我想用 df.loc[0:2,'Q0'] 中的值替换 df.loc[3:8,'Q0'] 中的值! =df.loc[3,'Q0']

结果应如下所示:

index df['Q0']
0         1
1         2
2         3
3         1
4         2
5         3
6         1
7         2
8         3
9         2
10        4
11        7

我尝试了以下行:

df.loc[3:8,'Q0'].where(~df.loc[0,'Q0']!=df.loc[3,'Q0']),other=df.loc[0:2,'Q0'],inplace=True)

或

df['Q0'].replace(to_replace=df.loc[3:8,'Q0'], value=df.loc[0:2,'Q0'], inplace=True)

但它不起作用。很可能我做错了什么。 有什么建议吗?

【问题讨论】:

    标签: python pandas itertools cycle


    【解决方案1】:

    你可以使用cycle函数:

    from itertools import cycle
    
    c = cycle(df["Q0"][0:3])
    if df.Q0[0] != df.Q0[3]: 
      df["Q0"][3:8] = [next(c) for _ in range(5)] 
    

    【讨论】:

    • 如果条件很简单,不是问题主要问题@jezrael
    • 解释一下cycle函数的作用会很好。
    • 这与意见无关,它要么会失败,要么会成功。
    • @jezrael 如果你觉得你有更好的答案,请发帖。
    【解决方案2】:

    感谢您的回复。我尝试了这些建议,但遇到了一些问题:

    @adnanmuttaleb - 当我在超过 1 列(例如 12x2 或更大)的数据框中应用该函数时,我注意到 df.Q0[8] 中的值没有改变。为什么?

    @jezrael - 当我适应你的建议时,我得到了错误:

    ValueError: cannot copy sequence with size 5 to array axis with dimension 6
    

    当我将范围更改为 6 时,我得到了错误的结果

    import pandas as pd
    from itertools import cycle
    
    data={'Q0':[1,2,3,5,5,6,7,8,3,2,4,7],
          'Q0_New':[0,0,0,0,0,0,0,0,0,0,0,0]}
    df = pd.DataFrame(data)
    
    ##### version 1
    
    c = cycle(df["Q0"][0:3])
    if df.Q0[0] != df.Q0[3]: 
      df['Q0_New'][3:8] = [next(c) for _ in range(5)] 
    
    ##### version 2
    
    d = cycle(df.loc[0:3,'Q0'])
    if df.Q0[0] != df.Q0[3]: 
      df.loc[3:8,'Q0_New'] = [next(d) for _ in range(6)] 
    

    为什么我们会有不同的行为以及需要进行哪些更正?

    再次感谢大家。

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 2020-01-02
      • 2022-11-30
      • 1970-01-01
      • 2013-12-27
      相关资源
      最近更新 更多