我正在使用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'))
但它不像我想的那样有效。
谢谢!
答案 0 :(得分:2)
我刚创建了一个包含所有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
列值。
答案 1 :(得分:0)
如果我理解正确,这样的事情就行了。使用以下内容基于原始数据框架创建更大的DataFrame(但在此示例中,行数为21x):
max_move = df_merged['max_move_%'][0] # 10 in this case
num_rows_needed = max_move * 2 + 1 # 21 in this case
new = pd.concat([df_merged] * num_rows_needed).reset_index(drop=True)
然后添加新列:
new['true_move'] = [i for i in range(-max_move, max_move + 1)]
new['price_new'] = new['price'] + new['true_move']
这会在您的问题中发布所需的结果。
根据您的较大数据集的外观,可能需要稍微调整一下。如果这不能满足您的需求,请使用代表性数据集编辑您的问题以进行测试。