python - 在特定位置将值分配给熊猫数据框的问题
问题描述
我在将值分配给特定位置(列和索引)的数据框时遇到问题。首先,我创建一个空数据框:
self.timeseries = pd.DataFrame(
columns = ["temperature", "state_of_charge", "m_ice", "m_water"],
index = pd.date_range(
start = self.environment.start,
end = self.environment.end,
freq = self.environment.time_freq,
name = "time"
)
)
后来我尝试为每个索引的每一列分配值:
self.timeseries.temperature.loc[timestamp] = self.current_temp
self.timeseries.state_of_charge.loc[timestamp] = self.state_of_charge
self.timeseries.m_ice.loc[timestamp] = self.m_ice /self.mass
self.timeseries.m_water.loc[timestamp] = self.m_water / self.mass
上面代码的第一行似乎有效。但是一旦到达第二行,我就会收到以下错误消息:
ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'>
在代码的其他部分,使用了完全相同的过程,并且可以正常工作。
非常感谢您提前提供的每一个帮助!
PS:我不知道,如果有必要,但附加信息:
我在 anaconda 1.9.12 中使用 spyder 3.3.6 (Python 3.7)
解决方案
您可以尝试迭代数据框的长度并使用整数索引位置将值填充到列中。这些值可以是计算值,这并不重要。逻辑将保持不变。
import pandas as pd
timeseries = pd.DataFrame(
columns = ["temperature", "state_of_charge", "m_ice", "m_water"],
index =pd.date_range(start ='01-01-2018 00:00:00',
end ='01-02-2018 00:00:00', freq='0.25H')
)
for i in range(len(timeseries)):
# this an example, can be any calculated value or function return #
timeseries.temperature.iloc[i] = i
timeseries.state_of_charge.iloc[i] = i+1
timeseries.m_ice.iloc[i] = i+2
timeseries.m_water.iloc[i] = i+3
print(timeseries)
temperature state_of_charge m_ice m_water
2018-01-01 00:00:00 0 1 2 3
2018-01-01 00:15:00 1 2 3 4
2018-01-01 00:30:00 2 3 4 5
2018-01-01 00:45:00 3 4 5 6
2018-01-01 01:00:00 4 5 6 7
... ... ... ... ...
2018-01-01 23:00:00 92 93 94 95
2018-01-01 23:15:00 93 94 95 96
2018-01-01 23:30:00 94 95 96 97
2018-01-01 23:45:00 95 96 97 98
2018-01-02 00:00:00 96 97 98 99
推荐阅读
- azure - 手动更改配置文件后,Ambari 是否恢复配置?
- ios - Google 放置 iOS sdk,按 lat,long 位置获取位置
- angular - Msal Angular Preview Azure AD 同意范围和访问令牌版本错误
- ios - 使用自定义动画呈现嵌入在导航控制器中的视图控制器
- redmine - Redmine、SMTP 和 Mandrill 自定义标题模板
- django - Django 1.11 多对多
- spring - 创建名称为“customerController”的 bean 时出错:通过字段“customerDAO”表示的依赖关系不满足;
- xamarin.forms - Stacklayout 中的 Xamrin Forms RelativeLayout 显示空白屏幕
- javascript - d3 中的条形位置与轴不匹配
- angular - 如何专注于特定的 mat-tab