尝试在pandas中重新索引数据帧时,我有一种奇怪的行为。我的Pandas版本是0.10.0,我使用的是Python 2.7。 基本上,当我加载数据帧时:
eurusd = pd.DataFrame.load('EUR_USD_30Min.df').drop_duplicates().dropna()
eurusd
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 119710 entries, 2003-02-02 17:30:00 to 2012-12-28 17:00:00
Data columns:
open 119710 non-null values
high 119710 non-null values
low 119710 non-null values
close 119710 non-null values
dtypes: float64(4)
然后我尝试在更大的日期范围内重新索引:
newindex = pd.DateRange(datetime.datetime(2002,1,1), datetime.datetime(2012,12,31), offset=pd.datetools.Minute(30))
newindex
<class 'pandas.tseries.index.DatetimeIndex'>
[2002-01-01 00:00:00, ..., 2012-12-31 00:00:00]
Length: 192817, Freq: 30T, Timezone: None
尝试重新索引数据帧时,我会遇到奇怪的行为。如果我重新索引数据集的一个较大部分,我会收到此错误:
eurusd[29558:29560].reindex(index=newindex)
Exception: Reindexing only valid with uniquely valued Index objects
但是,如果我对上面两个数据子集做同样的事情,我不会得到错误:
这是第一个子集,没有问题,
eurusd[29558:29559].reindex(index=newindex)
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 192817 entries, 2002-01-01 00:00:00 to 2012-12-31 00:00:00
Freq: 30T
Data columns:
open 1 non-null values
high 1 non-null values
low 1 non-null values
close 1 non-null values
dtypes: float64(4)
这是第二个子集,仍然没有问题,
eurusd[29559:29560].reindex(index=newindex)
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 192817 entries, 2002-01-01 00:00:00 to 2012-12-31 00:00:00
Freq: 30T
Data columns:
open 1 non-null values
high 1 non-null values
low 1 non-null values
close 1 non-null values
dtypes: float64(4)
我真的为此疯狂,并且无法理解这个原因。似乎数据框是重复的,并且重复的索引是“干净的”......如果你愿意,我可以提供数据框的pickle文件。
答案 0 :(得分:6)
您可以通过索引进行分组并获取第一个条目(请参阅docs):
df.groupby(level=0).first()
示例:
In [1]: df = pd.DataFrame([[1], [2]], index=[1, 1])
In [2]: df
Out[2]:
0
1 1
1 2
In [3]: df.groupby(level=0).first()
Out[3]:
0
1 1