【问题标题】:String row-index in pd.read_csv causes error "The label [1] is not in the [index]"pd.read_csv 中的字符串行索引导致错误“标签 [1] 不在 [索引] 中”
【发布时间】:2016-02-08 22:50:32
【问题描述】:

我正在将 CSV 导入 pandas 数据框。当我这样做时,我将索引列设置为 0,即列出的索引(0 到 10)。我收到错误键错误:标签 [1] 不在 [index] 中。

我已多次检查数据以确保第一列是数字列表。有关如何解决此问题的任何提示?

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

【问题讨论】:

标签: python pandas csv indexing


【解决方案1】:

您必须在 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)

【讨论】:

  • 谢谢!我一直坚持这一点。
  • @JeremyLewallen:我在 4 行中添加了一个最短的方法 :)
  • 谢谢。我不知道这是可能的。 :)
  • 不,您不需要在每次使用数字查找索引时都申请str()。您只需在 csv 读取时一劳永逸地将索引设为字符串列。使用 `read_csv(index_col = ...) 查看 How to read index data as string with pandas.read_csv()? 并设置其 dtype。
猜你喜欢
  • 2016-05-18
  • 2018-04-06
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多