【问题标题】:Combine a part of values合并部分值
【发布时间】:2017-11-29 09:54:21
【问题描述】:

我有一个这样的数据框:

In: 
daten["Gas"].head(5)

Out: 
2016-12-09 10:22:00       2.1
2016-12-09 10:22:15       5.1
2016-12-09 10:22:30       3.2
2016-12-09 10:22:45       2.0
2016-12-09 10:23:00       1.1

我将使用这些值的一部分进行计算并将它们放回列中。

von = pd.to_datetime("12.09.16 10:22:15",infer_datetime_format=True)
bis = pd.to_datetime("12.09.16 10:22:45",infer_datetime_format=True)
auswahl = daten.loc[von:bis]
auswahl["Gas_neu"] = auswahl["Gas"] - 2 // just an example

new Out:
2016-12-09 10:22:00 2.1
2016-12-09 10:22:15 3.1
2016-12-09 10:22:30 1.2
2016-12-09 10:22:45 0.0
2016-12-09 10:23:00 1.1

很遗憾 .combine 在这种情况下不起作用,还有其他方法吗?

这是计算

auswahl["Gas_1"] = auswahl["Gas"]

auswahl["Gas_1"] = (auswahl["Gas_1"] - auswahl["Gas_1"].shift()).fillna(0)

auswahl["Gas_1"] = auswahl["Gas_1"] * 2400

【问题讨论】:

  • 你能提供给定示例的预期输出吗?
  • 我做了,叫“新出”

标签: pandas overwrite combinelatest


【解决方案1】:

你可以使用:

daten.loc[von:bis, 'Gas'] -=  2
print (daten)
                     Gas
2016-12-09 10:22:00  2.1
2016-12-09 10:22:15  3.1
2016-12-09 10:22:30  1.2
2016-12-09 10:22:45  0.0
2016-12-09 10:23:00  1.1

什么是相同的:

daten.loc[von:bis, 'Gas'] =  daten.loc[von:bis, 'Gas'] - 2
print (daten)
                     Gas
2016-12-09 10:22:00  2.1
2016-12-09 10:22:15  3.1
2016-12-09 10:22:30  1.2
2016-12-09 10:22:45  0.0
2016-12-09 10:23:00  1.1

对于新列:

daten.loc[von:bis, 'Gas_neu'] =  (daten.loc[von:bis, 'Gas'] - 2)
daten['Gas_neu'] = daten['Gas_neu'].fillna(daten['Gas'])
print (daten)
                     Gas  Gas_neu
2016-12-09 10:22:00  2.1      2.1
2016-12-09 10:22:15  5.1      3.1
2016-12-09 10:22:30  3.2      1.2
2016-12-09 10:22:45  2.0      0.0
2016-12-09 10:23:00  1.1      1.1

没有过滤的解决方案:

daten['Gas_1'] = (daten["Gas"] - daten["Gas"].shift()).fillna(0).mul(2400)
daten['Gas_2'] = daten["Gas"].diff().fillna(0).mul(2400)
print (daten)
                     Gas   Gas_1   Gas_2
2016-12-09 10:22:00  2.1     0.0     0.0
2016-12-09 10:22:15  5.1  7200.0  7200.0
2016-12-09 10:22:30  3.2 -4560.0 -4560.0
2016-12-09 10:22:45  2.0 -2880.0 -2880.0
2016-12-09 10:23:00  1.1 -2160.0 -2160.0

还有过滤:

von = pd.to_datetime("12.09.16 10:22:15",infer_datetime_format=True)
bis = pd.to_datetime("12.09.16 10:22:45",infer_datetime_format=True)
daten.loc[von:bis, 'Gas_neu'] =  daten.loc[von:bis, 'Gas'].diff().fillna(0).mul(2400)
daten['Gas_neu'] = daten['Gas_neu'].fillna(daten['Gas'])
print (daten)
                     Gas  Gas_neu
2016-12-09 10:22:00  2.1      2.1
2016-12-09 10:22:15  5.1      0.0
2016-12-09 10:22:30  3.2  -4560.0
2016-12-09 10:22:45  2.0  -2880.0
2016-12-09 10:23:00  1.1      1.1

【讨论】:

  • 计算有点复杂。
  • 查看编辑后的答案。我用diff改进你的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2017-04-29
  • 1970-01-01
  • 2020-11-03
  • 2013-12-04
  • 1970-01-01
  • 2016-05-29
相关资源
最近更新 更多