我有一个数据框,其中包含每个新行累积的统计数据。每天都会添加一个新行。现在我想迭代我的列,以便从上面的行中减去每一行(从最后开始)。新值应放入新列。 这就是我的数据帧的外观,而'diff'列中的值是我想要的结果:
time In diff
0 2017-06-26 7.086
1 2017-06-27 8.086 1
2 2017-06-28 10.200 2.114
这就是我提出的:
for x in df['In']:
df['diff'] = df.iloc[-1] - df.iloc[-2]
但不是这样。如何从最后一行开始循环,如何使iloc更具动态性?有人可以帮忙吗? 谢谢!
答案 0 :(得分:4)
您可以使用Series.diff
:
GetWindowLongPtrA
答案 1 :(得分:3)
使用library(shiny)
library(DT)
ui <- shinyUI(fluidPage(
h1('Testing TableTools'),
mainPanel(
dataTableOutput('display')
)
))
Names <- c("",names(mtcars))
FooterNames <- c(rep("",4),Names[5:6],rep("",6))
server <- function(input, output, session) {
sketch <- htmltools::withTags(table(
tableHeader(Names),tableFooter(FooterNames)
))
opts <- list(
dom = 'Bfrtip', buttons = list('colvis','print',list(extend='collection',text='Download',buttons = list('copy','csv','excel','pdf'))),
footerCallback = JS(
"function( tfoot, data, start, end, display ) {",
"var api = this.api(), data;",
"$( api.column(5).footer()).html('SubTotal: '+",
"api.column(5).data().reduce( function ( a, b ) {",
"return a + b;",
"} )",
");",
"$( api.column(4).footer()).html('SubTotal: '+",
"api.column(4).data().reduce( function ( a, b ) {",
"return a + b;",
"} )",
");","}")
)
output$display <- DT::renderDataTable(container = sketch,extensions = 'Buttons',options = opts,{
mtcars
})
}
shinyApp(ui = ui, server = server)
.container {
display: flex;
flex-flow: row wrap;
align-content: flex-start;
}
.card {
flex: 1 1 0;
padding: 0.5rem;
}
答案 2 :(得分:1)
可以使用shift()
:
df
In time
0 7.086 2017-06-26
1 8.086 2017-06-27
2 10.200 2017-06-28
df.sort_values('time', inplace=True)
df['diff'] = df['In'] - df['In'].shift(1)
df
In time diff
0 7.086 2017-06-26 NaN
1 8.086 2017-06-27 1.000
2 10.200 2017-06-28 2.114
答案 3 :(得分:1)
以下是您需要做的一切。
df['diff'] = df.In - df.In.shift(1)
# In [16]: df
# Out[16]:
# time In diff
# 0 2017-06-26 7.086 NaN
# 1 2017-06-27 8.086 1.000
# 2 2017-06-28 10.200 2.114