Pandas groupby.sum()工作不正常?

2024-10-06 11:52:59 发布

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

我在一个叫PredictIt的网站上赌博。我已经下载了一个csv文件,其中包含了我所赌过的所有市场的所有损益。我叫它dat

csv有每笔交易的损益数据(“ProfitLoss”),以及我交易的市场名称(“MarketName”)。在将财务数据转换为浮动(必须删除美元,并且必须删除负数的()。但market_groups文件中没有损益栏。它添加了其他数字列,但不是我修改的那个

for index, row in dat.iterrows():
    if dat['ProfitLoss'][index][0] == '(':
        length = len(dat['ProfitLoss'][index])
        dat['ProfitLoss'][index] = float(dat['ProfitLoss'][index][2:length-1]) * -1
    else:
        length = len(dat['ProfitLoss'][index])
        dat['ProfitLoss'][index] = float(dat['ProfitLoss'][index][1:length-1])
    print(type(dat['ProfitLoss'][index]))

market_groups = dat.groupby(['MarketName']).sum()

Tags: 文件csvindexlen市场交易floatmarket
1条回答
网友
1楼 · 发布于 2024-10-06 11:52:59

问题在于,“ProfitLoss”系列的dtype是从原始数据(即字符串)推断出来的。您需要将序列设置为浮动,或者在sum()中设置numeric_only=False

也就是说,更改“ProfitLoss”的dtype

dat = dat.astype({'ProfitLoss': 'float'})
market_groups = dat.groupby(['MarketName']).sum()

或仅将数值_设置为False

market_groups = dat.groupby(['MarketName']).sum(numeric_only= False)

应该有用

还想指出dat['ProfitLoss'][index] = float(dat['ProfitLoss'][index][1:length-1])中的-1可能不在那里?我认为您的意思是删除结尾括号),但在else子句中不需要这样做

相关问题 更多 >