【问题标题】:Error when trying to .insert() into dataframe尝试将 .insert() 插入数据框时出错
【发布时间】:2019-07-10 17:52:11
【问题描述】:

我有一些代码需要一个 csv 文件,它每天找到最小值/最大值,然后告诉我发生的时间。我还有 2 个变量来查找最大值/最小值的百分比。

这是当前数据帧的输出

>Out
       High   Low
10:00   6.0  10.0
10:05  10.0   3.0
10:10   1.0   7.0
10:15   1.0   NaN
10:20   4.0   4.0
10:25   4.0   4.0
10:30   5.0   1.0
10:35   5.0   6.0
10:40   3.0   2.0
10:45   4.0   5.0
10:50   4.0   1.0
10:55   3.0   4.0
11:00   4.0   5.0
>

然后我有 2 个用于高/低百分比的变量..(仅显示 ph)

>[84 rows x 2 columns]
Time
10:00    0.015306
10:05    0.025510
10:10    0.002551
10:15    0.002551
10:20    0.010204
10:25    0.010204
>

我尝试执行 .insert(),但收到此错误。

TypeError: insert() 接受 4 到 5 个位置参数,但给出了 6 个

这是我的代码

#adding % to end of dataframe
result.insert(3,"High %", ph, "Low %", pl)

import pandas as pd
from matplotlib import pyplot as plt

df = pd.read_csv("C:\\Users\\me\\Downloads\\file.csv", encoding = "ISO-8859-1")


#High grouped by Date
df2 = df.loc[df.groupby('Date')['High'].idxmax()]


#dropping columns of no use
df2.drop(['Ticker','Open','Low','Close'], axis=1, inplace=True)

#creating a variable to bucket the time
TH = df2.groupby('Time').size()

#Low grouped by Date
df3 = df.loc[df.groupby('Date')['Low'].idxmin()]

#dropping columns of no use
df3.drop(['Ticker','Open','Low','Close'], axis=1, inplace=True)

#creating a variable to bucket the time
TL = df3.groupby('Time').size()

#Merging Both Dataframes
frames = [TH, TL]
result = pd.concat((frames), axis = 1)
result.columns = ['High','Low']

#Percentage
ph = TH/TH.sum()
pl = TL/TL.sum()

我希望输出在第 3 列和第 4 列中显示 %

>Out
       High   Low    % High    %Low
10:00   6.0  10.0    .015306   
10:05  10.0   3.0    .025510
10:10   1.0   7.0    .002551
10:15   1.0   NaN    .002551
10:20   4.0   4.0    .010204
10:25   4.0   4.0    .010204

>

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

使用 insert 一次只能添加一列。当您打算在数据框的末尾添加新列时,您甚至不需要插入:

#adding % to end of dataframe
result["High %"] = ph
result["Low %"] = pl

如果你坚持使用插入,正确的语法应该是:

result.insert(2, "High %", ph)
result.insert(3, "Low %", pl)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多