【问题标题】:Pandas replacing the one column value with other熊猫用另一列值替换一列值
【发布时间】:2018-11-04 19:59:54
【问题描述】:

这里是示例数据:

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

我愿意用PreviousCandleColor 替换CurrentCandleColor 值,但CurrentCandleColor 的第0 个值应该是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'>   

请帮帮我。

【问题讨论】:

  • 这叫换档
  • df['CurrentCandleColor'] = df['PreviousCandleColor'].shift()
  • @Dark - 同意你的看法。
  • 但这对我不起作用。你试过了吗。请告诉我。
  • @JafferWilson - 你能解释更多吗?

标签: python-3.x pandas python-3.5


【解决方案1】:

如果这里没有NaNs,则使用shiftfillna

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'])

如果可能,NaNs 值首先获取列的最后一个值,然后返回:

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

【讨论】:

  • 也许评论会更好。 shift na 有这么多答案?
  • 帮助很大。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 2014-04-01
  • 2015-01-19
相关资源
最近更新 更多