Панды, заменяющие одно значение столбца другим - PullRequest
0 голосов
/ 25 мая 2018

Вот пример данных:

Time,RangeGreen,RangeRed,DistanceGreenRed,SlopeGreen,SlopeRed,PreviousCandleColor,CurrentCandleColor
2018.04.02 00:01:01,30-40,20-30,14.42241040084485,0.002837507264410963,-0.002233901393132696,Green,indecisive
2018.04.02 00:03:06,40-50,30-40,9.228956001044772,3.969502900848433,7.203315124348411,Green,indecisive
2018.04.02 00:04:06,10-20,30-40,-13.69498672180752,-19.36590965829607,-2.850639197642629,Red,indecisive

Я готов заменить значения CurrentCandleColor на PreviousCandleColor, но 0-е значение CurrentCandleColor должно быть 1-м значением PreviousCandleColor.

Следовательно, мое окончательное значение должно быть:

Time,RangeGreen,RangeRed,DistanceGreenRed,SlopeGreen,SlopeRed,PreviousCandleColor,CurrentCandleColor
2018.04.02 00:01:01,30-40,20-30,14.42241040084485,0.002837507264410963,-0.002233901393132696,Green,Green
2018.04.02 00:03:06,40-50,30-40,9.228956001044772,3.969502900848433,7.203315124348411,Green,Red
2018.04.02 00:04:06,10-20,30-40,-13.69498672180752,-19.36590965829607,-2.850639197642629,Red,indecisive

Я пытался переместить его примерно так;

df['CurrentCandleColor'] = df[1:'PreviousCandleColor']

Но я получил следующую ошибку:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.range.RangeIndex'> with these indexers [PreviousCandleColor] of <class 'str'>   

Пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 25 мая 2018

Используйте shift с fillna, если нет NaNs здесь:

a = df.loc[df.index[-1], 'CurrentCandleColor']
df['CurrentCandleColor'] = df['PreviousCandleColor'].shift(-1).fillna(a)
print (df)
                  Time        ...         CurrentCandleColor
0  2018.04.02 00:01:01        ...                      Green
1  2018.04.02 00:03:06        ...                        Red
2  2018.04.02 00:04:06        ...                 indecisive

[3 rows x 8 columns]

Или:

df['CurrentCandleColor'] =df['PreviousCandleColor'].shift(-1).fillna(df['CurrentCandleColor'])

Если возможно, значения NaN s сначала получают последнее значение столбца, а затем возвращают обратно:

last = df['CurrentCandleColor'].values[-1]
df['CurrentCandleColor'] = df['PreviousCandleColor'].shift(-1)
df.loc[df.index[-1], 'CurrentCandleColor'] = last
...