为pandas datafram中的单元格赋值

2024-10-01 02:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遍历该文件,并希望根据索引和列设置DataFrame中单元格的值。在

f = "D:/Technical_Data/1pep.csv"
df = pd.read_csv(f, header=0, sep=',')
save_file = "D:/Result_of_TA/" + "def.csv"
qbfile = open(save_file,"r")
for aline in qbfile.readlines():
    values = aline.split(",")
    if values[58].strip()=='BUY' :
       no_of_shares = price/float(values[4])
    if values[58].strip()=='SELL' :
        price = no_of_shares * float(values[4]) 
    df.ix[values[0],'Price'] = price
qbfile.close()
df.to_csv(save_file)

我正处于错误之下

^{pr2}$

两个文件中的列0都是索引


Tags: 文件ofcsvnodfifsavefloat
1条回答
网友
1楼 · 发布于 2024-10-01 02:19:08

我建议使用pandas同时读取csv文件,而不是循环使用save_file。然后,您可以创建各种索引方案和计算来将数据从qb移动到1pep。你可以这样构造你的代码

import pandas as pd

# File locations
pep1_file = 'D:/Technical_Data/1pep.csv'
qb_file = 'D:/Result_of_TA/def.csv.csv'

# Read csv files
pep1 = pd.read_csv(pep1_file, header=0, sep=',')
qb = pd.read_csv(qb_file, header=0, sep=',')

# Process data    
# Find rows with buy in 58th col?
buy_index = qb.iloc[:, 58].str.contains('BUY')

# Find rows with sell in 58th col?
sell_index = qb.iloc[:, 58].str.contains('SELL')

# Get something from 4th col in buy rows?
something_from_purchase = qb.ix[buy_index, 4].astype(float)

# Derive number of shares 
# Where do you get your initial price from?
# It is used before it is assigned if buy row happens first in the original code?
no_of_shares = price / something_from_purchase

# Get something from 4th col in sell rows?
something_from_sale = qb.ix[sell_index, 4].astype(float)

# Derive price
# Where do you get your initial no_of_shares from?
# It is used before it is assigned if sell row happens first in the original code?
price = no_of_shares * something_from_sale

# Assign pep1 price based on qb index
pep1.loc[qb.index, 'Price'] = price

# Then write csv file
# Are sure you want to overwrite?
pep1.to_csv(qb_file)

现在你的代码还不清楚。{{cd7>可能有一些循环依赖关系。如果没有一些示例数据或结构说明,则无法建议具体代码。在

相关问题 更多 >