0

python pandas DataFrame では、インデックスの値を 1 行で更新したいと思います (DataFrame が非常に大きいため、できればその場で)。

インデックスは DatetimeIndex であり、DataFrame には複数の列が含まれる場合があります。

例えば:

In [1]: import pandas as pd
In [2]: pd.DataFrame({'DATA': [1,2,3]},
                      index=[pd.Timestamp(2011,10,01,00,00,00),
                             pd.Timestamp(2011,10,01,02,00,00),
                             pd.Timestamp(2011,10,01,03,00,00)])
Out[5]: 
                     DATA
2011-10-01 00:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

望ましい出力は次のとおりです。

                     DATA
2011-10-01 01:00:00     1   <---- Index changed !!!
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

大きな DataFrames に対してこれを行う簡単な (そして安価な) 方法はありますか?

サンプルの場所がわかっていると仮定します (たとえば、変更する必要があるのは n 番目の行です)。

4

2 に答える 2

2

で考えられる解決策の 1 つSeries.replaceですが、最初に convert が必要ですIndex.to_series

df.index = df.index
             .to_series()
             .replace({pd.Timestamp('2011-10-01'): pd.Timestamp('2011-10-01 01:00:00')})
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

Index.where(の新機能)を使用した別のソリューション0.19.0

df.index = df.index.where(df.index != pd.Timestamp('2011-10-01'),
                          [pd.Timestamp('2011-10-01 01:00:00')])

print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

drop新しい行を追加し、最後に古い行を削除するソリューションsort_index

df.loc[pd.Timestamp('2011-10-01 01:00:00')] = df.loc['2011-10-01 00:00:00', 'DATA']
df.drop(pd.Timestamp('2011-10-01 00:00:00'), inplace=True)
df.sort_index(inplace=True)
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

位置ではなく値で置き換える必要がある場合の別の解決策:

df.index.set_value(df.index, pd.Timestamp(2011,10,1,0,0,0), pd.Timestamp(2011,10,1,1,0,0))
print (df)
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3

コメントから変換indexする最後の解決策:numpy array

i = 0
df.index.values[i] = pd.Timestamp('2011-10-01 01:00:00')
print (df)          
                     DATA
2011-10-01 01:00:00     1
2011-10-01 02:00:00     2
2011-10-01 03:00:00     3
于 2016-10-31T11:17:21.857 に答える