簡體   English   中英

如何使用 for 循環和 if 語句將 append 行轉換為 pandas dataframe

[英]How to append rows to pandas dataframe with for loop and if statements

我正在嘗試將 append 的行復制到 dataframe,如果每行符合條件,則按照“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

現在,我不太清楚這段代碼的錯誤,我只是不知道如何修復錯誤。

這里不需要循環,只需使用傳入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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM