【问题标题】:How to append rows to pandas dataframe with for loop and if statements如何使用 for 循环和 if 语句将行附加到 pandas 数据帧
【发布时间】:2020-08-12 11:29:22
【问题描述】:

如果每行符合条件,我正在尝试复制这些行并将其附加到数据框中,次数与“qty1”中指示的一样多。

这是我迄今为止尝试过的代码:

import pandas as pd
row_list = [['a', 1, 4], ['b', 2, 5], ['c', 3, 6]]
columns = ['item', 'qty1', 'qty2']

df = pd.DataFrame(row_list, columns = columns)

for index, row in df.iterrows():
    if df.loc[index, 'qty1'] != 1: # apply only on lines where 'qty1' is different from 1
        df.append([row]*df.loc[index,'qty1']) # multiply and append the rows as many times as the column 'qty1' indicates
    else:
        pass

df

我得到以下结果(但没有任何反应):

    item qty1 qty2
0      a    1    4
1      b    2    5
2      c    3    6

虽然我正在寻找的是:

    item    qty1    qty2
0      a       1       4
1      b       2       5
2      b       2       5
3      c       3       6
4      c       3       6
5      c       3       6

现在,我不太清楚这段代码的错误,我只是不知道如何修复错误。

【问题讨论】:

    标签: python pandas dataframe for-loop if-statement


    【解决方案1】:

    这里不需要循环,只需使用Index.repeat 传递qty1 字段作为重复。然后使用loc 返回行。

    df.loc[df.index.repeat(df['qty1'])].reset_index(drop=True)
    

    [出]

      item  qty1  qty2
    0    a     1     4
    1    b     2     5
    2    b     2     5
    3    c     3     6
    4    c     3     6
    5    c     3     6
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 2019-04-13
      • 2017-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多