【问题标题】:Print row as many times as its value plus one turns up in other rows打印行的次数与其值加一的次数在其他行中出现
【发布时间】:2019-09-08 23:09:45
【问题描述】:

我想根据 imageno+1 出现的次数在新的 df (df2) 中打印每一行。所以在下面的数据中,第1行应该打印两次(有两个7),第2行两次,第3行两次,第4行一次(有一个8),第5行一次,等等。

import pandas as pd

print(df)
   x-position  y-position  imageno
1  220         220          6
2  627         220          6
3  620         220          6
4  220         220          7
5  628         220          7
6  621         220          8

df2 = pd.DataFrame(columns=['x-position', 'y-position', 'imageno'])

【问题讨论】:

    标签: python pandas loops dataframe rows


    【解决方案1】:

    IIUC,使用Series.value_counts 创建一个辅助系列,然后使用Series.mapindex.repeatDataFrame.loc 获得所需的次数或重复次数:

    df = pd.DataFrame({'x-position': {1: 220, 2: 627, 3: 620, 4: 220, 5: 628, 6: 621}, 'y-position': {1: 220, 2: 220, 3: 220, 4: 220, 5: 220, 6: 220}, 'imageno': {1: 6, 2: 6, 3: 6, 4: 7, 5: 7, 6: 8}})
    
    s = df['imageno'].value_counts()
    
    df2 = df.loc[df.index.repeat(df['imageno'].add(1).map(s).fillna(0).astype(int))]
    

    [出]

       x-position  y-position  imageno
    1         220         220        6
    1         220         220        6
    2         627         220        6
    2         627         220        6
    3         620         220        6
    3         620         220        6
    4         220         220        7
    5         628         220        7
    

    【讨论】:

    • 谢谢。我收到一个错误SyntaxError: unexpected EOF while parsing。你知道我该如何解决这个问题吗?
    • @sforbes hmmmm,如果您复制并粘贴上面的代码(包括示例数据),您会收到 EOF 吗?也许您在某处缺少右括号或右引号?
    • 错误信息是否提示了 SyntaxError 在代码中的位置?哪一行,哪一列等等?
    • 感谢您提供示例数据。使用您发送的代码,我收到错误 TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
    • 我无法重现该错误,可能是版本问题..?我更新了代码,添加了astype(int) 方法。你能再试一次吗?
    【解决方案2】:

    IIUC merge调整后'imageno'

    df.assign(imageno=df.imageno+1).merge(df[['imageno']],on='imageno').assign(imageno=lambda x : x['imageno']-1)
    Out[894]: 
       x-position  y-position  imageno
    0         220         220        6
    1         220         220        6
    2         627         220        6
    3         627         220        6
    4         620         220        6
    5         620         220        6
    6         220         220        7
    7         628         220        7
    

    【讨论】:

    • 谢谢。这行得通(没有错误消息),但我认为 imagenos 比它们应该的高一个?
    • 这行得通,谢谢。请问代码可以解释一下吗?
    • @sforbes 加一,所以当merge (6+1) 会和7 合并,合并后我们只需要减一,回到原来的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2016-02-17
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    相关资源
    最近更新 更多