【问题标题】:DataFrame error of constructor not properly called构造函数的 DataFrame 错误未正确调用
【发布时间】:2021-06-04 19:42:26
【问题描述】:

所以我有一个使用我的代码创建的数据框,当我使用 for 循环进行循环时 通过列并获得不同的结果以创建另一个数据框 我得到这个错误 DataFrame 构造函数没有正确调用!

这是我的代码

#get all trafficlights ids with traci
tlsID= traci.trafficlight.getIDList()
print(tlsID)

# loop through the trafficlights ids and save them to dataframe
for i in tlsID:
    df = pd.DataFrame(tlsID, columns=[i])
    i =+1

# remane the coulmn to any name you want
df.columns= ['tlsID']

# export your dataframe to csv file
df.to_csv('tlsID.csv', index=False)

# convert dataframe to strings
tlsID_df= df['tlsID'].astype(str)

# create an empty list to append new items to it
df3=[]
df4=[]
# loop through your dataframe
for i in tlsID_df:
    # get all lanes controlled by trafficlights (incoming lanes)and append to your list
    controlled_lanes= traci.trafficlight.getControlledLanes(i)
    appended = pd.DataFrame(controlled_lanes)
    df3.append(appended)
    i =+1

# put a name your column to use it later
col1= ['incoming']

# transfer your list to a dataframe
lanes= pd.concat(df3, ignore_index= True)

# remane your column
lanes.columns= col1

# drop duplicated rows
lanes= lanes.drop_duplicates()

# reset your index
lanes = lanes.reset_index(drop=True)
lanes.to_csv('incoming_links.csv', index=False)

lanes_df= lanes['incoming'].astype(str)
for i in lanes_df:
    # get all lanes controlled by trafficlights (incoming lanes)and append to your list
    lane= traci.lane.getLength(i)
    append = pd.DataFrame(lane)
    df4.append(append)
    i =+1
# put a name your column to use it later
col2= ['len']

# transfer your list to a dataframe
lanes_len= pd.concat(df4, ignore_index= True)

# remane your column
lanes_len.columns= col2

# drop duplicated rows
lanes_len= lanes_len.drop_duplicates()

# reset your index
lanes_len = lanes_len.reset_index(drop=True)

# export your dataframe to csv file
lanes_len.to_csv('lanes_len.csv', index=False)

我的错误出现在第二个 for 循环中

for i in lanes_df:
    # get all lanes controlled by trafficlights (incoming lanes)and append to your list
    lane= traci.lane.getLength(i)
    append = pd.DataFrame(lane)
    df4.append(append)
    i =+1

这个函数 - traci.lane.getLength(i) - 返回浮点数

可能是什么问题,因为我之前已经使用过它并且效果很好

【问题讨论】:

    标签: python pandas dataframe csv for-loop


    【解决方案1】:

    所以我想通了,问题是我的代码返回浮点数,我无法用浮点数创建数据帧

    所以我这样做了

    for i in lanes_df:
        # get all lanes controlled by trafficlights (incoming lanes)and append to your list
        lane= traci.lane.getLength(i)
        append = df4.append(lane)    
    
        i =+1
    
    lanes_len = pd.DataFrame(np.array([df4]).T)
    lanes_len.columns= ['len']
    

    我首先将所有值附加到我的列表中,然后使用 numpy 数组创建我的数据框(注意我使用转置将每个值附加到单独的行中)

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2017-07-27
      • 2021-09-27
      • 2019-02-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多