pd.read_csv中的字符串行索引导致错误“标签[1]不在[index]中”

2024-04-25 17:01:02 发布

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

我正在将CSV导入pandas数据帧。执行此操作时,我将索引列设置为0,这是列出的索引(0到10)。我收到错误密钥错误:标签[1]不在[索引]中。

我已经多次检查数据,以确保第一列是数字列表。有什么我能解决的线索吗?

from __future__ import division
import pandas as pd
import random
import math


#USER VARIABLES

#GAME VARIABLES

Passengers = 500

data = pd.read_csv("Problem2/data.csv", index_col=0)
print(data)

obs = len(data)

data["A"] = 0
data["B"] = 0
data["U"] = 0


for row in range(1,obs+1, 1):

    A = 0
    B = 0
    U = 0

    for i in range(1, Passengers + 1, 1):

        if data.loc[row, i] == "A":
            A += 1
        elif data.loc[row, i] == "B":
            B += 1
        else:
            U += 1


    data.loc[row, "A"] = A
    data.loc[row, "B"] = B
    data.loc[row, "U"] = U

ServiceLevels = range(170, 210,1)
for level in ServiceLevels:
    print(str(level) + " " + str(len(data[((data.A <= level))])/obs))

数据集=https://github.com/deacons2016/SimulationModels/blob/master/Exam1/Problem2/data.csv


Tags: csv数据inimportpandasfordata错误
1条回答
网友
1楼 · 发布于 2024-04-25 17:01:02

必须在for中使用str强制转换列。

In[60]: data = pd.read_csv(r'/Users/Desktop/data.csv', sep = ',', index_col = [0])

In[61]: obs = len(data)

In[62]: data["A"] = 0
        data["B"] = 0
        data["U"] = 0

In[63]: Passengers = 500

In[64]: for row in range(1,obs+1):
            print row
            A = 0
            B = 0
            U = 0
            for i in range(1, Passengers + 1, 1):
                if data.loc[row, str(i)] == "A":
                    A += 1
                elif data.loc[row, str(i)] == "B":
                    B += 1
                else:
                    U += 1
            data.loc[row, "A"] = A
            data.loc[row, "B"] = B
            data.loc[row, "U"] = U
1
.
.
10

最简单的方法是:

data = pd.read_csv(r'/Users/Desktop/data.csv', sep = ',', index_col = [0])

cols = data.columns
data['A'] = (data[cols] == 'A').astype(int).sum(axis=1)
data['B'] = (data[cols] == 'B').astype(int).sum(axis=1)
data['U'] = (data[cols] == 'U').astype(int).sum(axis=1)

相关问题 更多 >