DataFrame创建 - 重新编制索引

时间:2015-05-27 22:27:18

标签: python numpy dictionary pandas

我在熊猫中不断收到此错误:

raise Exception('Reindexing only valid with uniquely valued Index '
Exception: Reindexing only valid with uniquely valued Index objects

如果在尝试从字典中创建DataFrame时列名相同,我会理解这一点。

然而,我的不是。

这是我正在使用的字典 - 看起来像这样 - 非常像教程中给出的那样,不起作用:

d = {'Sample1': 4.121025    0.306828
4.119957    0.335473
4.096208    0.331831
...
0.824808    0.366679
0.745721    0.586742
Length: 406, 'Sample2': 3.444444    0.937468
3.315508    0.855920
...
0.928144    0.236640
0.918519    0.232346
Length: 991}

这是我用来生成这个字典的代码,其中一些细节不相关,但spec.Y和spec.X只是numpy数组:

d = dict()
for tab in self.tab_list:
    spec = tab.temp_spectra
    name = str(spec.spectra_name)
    d[name] = pd.Series(spec.Y, index=spec.X)
    print(name)
print(d)
df = pd.DataFrame(d)
print(df)

为什么会出现此错误的任何想法,以便我知道要修复后要做什么?列名似乎不是它,我在假设索引可以匹配或不匹配的情况下运行 - 这应该无关紧要 - 这就是我使用这个包的原因。我想要'哈希表'类型的感觉,X数组可以是不同的或相同的,重叠将把值放在同一行或者如果需要的话创建一​​个新的行,这样所有的都可以一起查看。

编辑:

我发现解决方案与我的一个数据集的索引中的重复条目有关(我的一个数据集是通过手工跟踪绘制的,因此得到一个X值的两个Y值)。 我将在回答我自己的问题时给出一些这方面的例子。

1 个答案:

答案 0 :(得分:1)

始终检查一个X值是否有2个Y值,或者数据帧的每个索引有两个值。 我手动跟踪图表中的一个数据集并创建数据,为一个X提供2 y值。

说明: 这是一个可编辑的小脚本:

import pandas as pd
import numpy as np

def f(i):
    return np.random.rand(i,)

# number of points in two spectra (two separate spectra of different length)
# possibly obtained on different equipment such that the pixels/values don't align
n1 = 450
n2 = 950
X1 = np.sort(f(n1))
X2 = np.sort(f(n2))
Y1 = f(n1)
Y2 = f(n2)

# make dataframe from the spectra
d = dict()
d['1'] = pd.Series(Y1, index=X1)
d['2'] = pd.Series(Y2, index=X2)
print(d)
df = pd.DataFrame(d)
print(df)

这是一个不是,并返回我得到的错误:

import pandas as pd
import numpy as np

def f(i):
    return np.random.rand(i,)

# number of points in two spectra (two separate spectra of different length)
# possibly obtained on different equipment such that the pixels/values don't align
n1 = 450
n2 = 950
# store X array to duplicate a value within it
X_ = f(n1)
X1 = np.sort(np.append(X_,X_[0]))
X2 = np.sort(f(n2))
Y_ = f(n1)
Y1 = np.append(Y_,Y_[0])
Y2 = f(n2)

# make dataframe from the spectra
d = dict()
d['1'] = pd.Series(Y1, index=X1)
d['2'] = pd.Series(Y2, index=X2)
print(d)
df = pd.DataFrame(d)
print(df)