Skip to main content
 首页 » 编程设计

Python:使用循环将行添加到现有数据框中

2024年09月07日11bonelee

我正在使用 pandas Python 库,我想向现有 DF 添加行并保留现有行。

我的数据是这样的:

product price   max_move_% 
  1     100      10 

我这样运行循环:

for i, row in df_merged.iterrows(): 
for a in range((row['max_move_%']) * (- 1), row['max_move_%']): 
    df_merged['price_new'] = df_merged['price'] * (1 - a / 100.00) 

我想得到:

product price   max_move_%  true_move     price_new 
1       100      10          -10            90 
1       100      10          -9             91 
 ..... 
1       100      10          10             110 

但是没有任何反应,df 看起来和以前一样。 我该怎么做才能向列添加新值并同时保留现有 df 中的数据?

我试过这个:

df_loop = [] 
for i, row in df_merged.iterrows(): 
    for a in range((row['max_move_%']) * (- 1), row['max_move_%'] + 1): 
    df_loop.append((df_merged['product'], df_merged['price'], f_merged['max_move_%'],a)) 
 
pd.DataFrame(df_loop, columns=('product','price','max_move_%','price_new')) 

但它并没有像我想象的那样工作。

谢谢!

请您参考如下方法:

我刚刚创建了一个包含所有 5 个所需列的新 DataFrame,以向其中添加行:

import pandas as pd 
 
df_merged = pd.DataFrame(data=[[1, 100, 10]], columns=['product', 'price', 'max_move_%']) 
print(df_merged) 
#    product  price  max_move_% 
# 0        1    100          10 
 
new_columns = ['product', 'price', 'max_move_%', 'true_move', 'price_new'] 
df_new = pd.DataFrame(columns=new_columns) 
 
idx = 0 
for i, row in df_merged.iterrows(): 
    for true_move in range((row['max_move_%']) * (- 1), row['max_move_%']+1): 
        price_new = df_merged.iloc[i]['price'] * (1 + true_move / 100.00) 
        df_new.loc[idx] = row.values.tolist() + [true_move, price_new] 
        idx += 1 
 
print(df_new) 
#     product  price  max_move_%  true_move  price_new 
# 0       1.0  100.0        10.0      -10.0       90.0 
# 1       1.0  100.0        10.0       -9.0       91.0 
# 2       1.0  100.0        10.0       -8.0       92.0 
# 3       1.0  100.0        10.0       -7.0       93.0 
# 4       1.0  100.0        10.0       -6.0       94.0 
# 5       1.0  100.0        10.0       -5.0       95.0 
# 6       1.0  100.0        10.0       -4.0       96.0 
# 7       1.0  100.0        10.0       -3.0       97.0 
# 8       1.0  100.0        10.0       -2.0       98.0 
# 9       1.0  100.0        10.0       -1.0       99.0 
# 10      1.0  100.0        10.0        0.0      100.0 
# 11      1.0  100.0        10.0        1.0      101.0 
# 12      1.0  100.0        10.0        2.0      102.0 
# 13      1.0  100.0        10.0        3.0      103.0 
# 14      1.0  100.0        10.0        4.0      104.0 
# 15      1.0  100.0        10.0        5.0      105.0 
# 16      1.0  100.0        10.0        6.0      106.0 
# 17      1.0  100.0        10.0        7.0      107.0 
# 18      1.0  100.0        10.0        8.0      108.0 
# 19      1.0  100.0        10.0        9.0      109.0 
# 20      1.0  100.0        10.0       10.0      110.0 

我刚刚修改了用于评估 price_new 列值的百分比变化公式。