python - 如何通过变量中的索引调用 pd.Dataframe?
问题描述
我需要按索引调用 pd.DataFrame 。通过 data.sample 提取它:
features = data.drop(['target'], axis=1)
target = data['target']
valid_indexes = data.sample(n=sample_size, replace=False, random_state=12345).index
train_indexes = data.drop(valid_indexes).index
结果似乎是正确的:
print(valid_indexes)
print(train_indexes)
Int64Index([184, 75, 10, 101, 240, 112, 211, 238, 186, 67,
...
207, 301, 99, 175, 9, 254, 157, 255, 260, 270],
dtype='int64', length=101)
Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 12,
...
286, 287, 289, 290, 292, 296, 297, 298, 299, 300],
dtype='int64', length=202)
但是当我尝试通过这些索引调用数据框时,我得到了这个:
features[[valid_indexes]]
target[[valid_indexes]]
KeyError: "None of [Index([(184, 75, 10, 101, 240, 112, 211, 238, 186, 67, 68, 156, 87, 35, 147, 20, 288, 181, 173, 222, 57, 302, 250, 110, 278, 33, 103, 115, 55, 85, 120, 40, 30, 187, 163, 50, 54, 11, 170, 242, 150, 244, 239, 183, 225, 280, 16, 73, 52, 193, 132, 294, 188, 295, 106, 141, 100, 151, 291, 47, 18, 97, 224, 174, 53, 234, 232, 128, 205, 71, 293, 88, 216, 169, 258, 134, 223, 168, 164, 272, 259, 38, 269, 70, 127, 161, 219, 233, 130, 197, 241, 207, 301, 99, 175, 9, 254, 157, 255, 260, ...)], dtype='object')] are in the [columns]"
当我尝试通过以下方式调用数据时: features[2:14] 我得到正确的数据框。但是我使用变量的方式在某种程度上是错误的。有哪些可能的解决方案?
解决方案
推荐阅读
- angular - Angular HttpClient 帖子
- ios - 更改 UISegmentedControl 中特定段的标题文本颜色?
- azure-active-directory - 如何在 Azure AD SSO 注销后序列期间解决此 CORS 错误?
- python-3.x - Python 高级套接字通信
- spring-kafka - 如何使用 spring-kafka 再次发送消息
- sas - 如果 SAS 表中存在列,则返回 TRUE 值
- python - Pycharm 在我尝试导入它时说没有名为“kivy”的模块,尽管 Kivy 在 IDE 上工作
- momentjs - 使用 moment-countdown.js 加上 countdown.js 总是抛出 Uncaught TypeError: moment(...).countdown is not a function
- apostrophe-cms - 将片段加入模块时编辑器模式保存期间的撇号CMS错误
- c - 信号处理程序是否需要包含在进程的每个可能的上下文中?