按索引级别为 Pandas Multiindex DataFrame 赋值

2023-12-30

我有一个 Pandas 多索引数据框,我需要为系列中的一列分配值。该系列与数据帧的第一级索引共享其索引。

import pandas as pd
import numpy as np
idx0 = np.array(['bar', 'bar', 'bar', 'baz', 'foo', 'foo'])
idx1 = np.array(['one', 'two', 'three', 'one', 'one', 'two'])
df = pd.DataFrame(index = [idx0, idx1], columns = ['A', 'B'])
s = pd.Series([True, False, True],index = np.unique(idx0))
print df
print s

out:

             A    B
bar one    NaN  NaN
    two    NaN  NaN
    three  NaN  NaN
baz one    NaN  NaN
foo one    NaN  NaN
    two    NaN  NaN

bar     True
baz    False
foo     True
dtype: bool

这些不起作用:

df.A = s # does not raise an error, but does nothing
df.loc[s.index,'A'] = s # raises an error

预期输出:

             A     B
bar one    True   NaN
    two    True   NaN
    three  True   NaN
baz one    False  NaN
foo one    True   NaN
    two    True   NaN

系列(和字典)可以像带有 map 和 apply 的函数一样使用(感谢 @normanius 改进语法):

df['A'] = pd.Series(df.index.get_level_values(0)).map(s).values

或者类似地:

df['A'] = df.reset_index(level=0)['level_0'].map(s).values

Results:

A    B
bar one     True  NaN
    two     True  NaN
    three   True  NaN
baz one    False  NaN
foo one     True  NaN
    two     True  NaN
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按索引级别为 Pandas Multiindex DataFrame 赋值 的相关文章

随机推荐

  • “@reify”有什么作用以及何时使用?

    我在用户体验设计金字塔教程 http docs pylonsproject org projects pyramid tutorials en latest humans creatingux step06 index html 我不太明白
  • 使用 Angular-cli 在 Angular2 中进行本地化

    Angular 有没有本地化工具2使用时Angular cli 我遇到了这个链接 https devblog dymel pl 2016 11 03 angular2 and i18n translate your app 从 11 月开始
  • 安装 AllegroServe

    我目前正在阅读 Peter Seibel 的书 Practical Common Lisp 正在阅读第 26 章 Web 编程 在第 366 页 它说 第一步是将 AllegroServe 代码加载到 Lisp 图像中 在 Allegro
  • Android 上的 libcurl CURLE_SSL_CACERT_BADFILE 错误

    所以我尝试将 libcurl 与 JNI 一起使用 但它返回 CURLE SSL CACERT BADFILE 错误 这是我的代码 JNI 端 static size t WriteCallback void contents size t
  • Tkinter 在 Frames 中添加菜单栏

    我正在使用此处答案中发布的代码在 tkinter 中的两个框架之间切换 https stackoverflow com questions 7546050 switch between two frames in tkinter作者 Bry
  • Javascript:如何删除for循环中的最后一个逗号

    如何从此函数中删除最后一个逗号 for var i 0 i lt 100 i if i 2 0 div innerHTML l else div innerHTML 首先 使用数组而不是字符串来求和字符串 这样速度更快 第二 var arr
  • 如何制作长度为5的随机数字和字母字符串? [复制]

    这个问题在这里已经有答案了 可能的重复 这是生成随机字符字符串的好方法吗 https stackoverflow com questions 976646 is this a good way to generate a string of
  • jQuery ui Sortable 可以表现得像 gridster 吗?

    是否可以得到jQuery ui 可排序网格 http jqueryui com sortable display grid表现得像gridster http gridster net 为什么不使用网格斯特 因为它不适用于 IE9 以下的任何
  • 如何使用 ggrepel 抑制警告

    ggrepel允许通过排斥彼此太近的标签来避免文本标签重叠 该算法取决于查看窗口大小 并且当窗口大小更改时会发生回调 如果算法无法避免给定窗口大小的重叠 则会发出警告 Warning messages 1 ggrepel 178 unlab
  • 转换函数指针

    我正在编写一个函数 它接收一个指向比较函数的指针和一个数组MyStructs并应该根据比较函数对数组进行排序 void myStructSort struct MyStruct arr int size int comp const str
  • 更改 iOS XCode 项目中的产品名称宏

    我在上面构建了我的 iPhone 代码苹果的示例项目 http developer apple com library ios samplecode LazyTableImages Introduction Intro html 当应用程序
  • UTF8 与宽字符?

    我似乎在思考某些事情时遇到了一些困难 我正在尝试创建一个 C 函数来将 UTF8 转换为 Wide 我开始谷歌搜索 发现了 Boost 和 ICU 两者看起来都太大了 然后我找到了 utf cpp 头库 看起来不错 我通过这里的一些线程发现
  • 将文本设置为整数值

    我想设置一个TextView作为整数的值 希望像这样 tv setText int 我尝试了这个 但出现了这个错误 另外 我的整数值在另一个类中 D AndroidRuntime Shutting down VM E AndroidRunt
  • 使用 python-pptx 添加项目符号列表

    我正在使用 python pptx 库进行 pptx 操作 我想在 pptx 文档中添加项目符号列表 我使用以下代码片段添加列表项 p text frame add paragraph run p add run p level 0 run
  • 如何只获取一次脚本

    所以这是一个简化的问题 我将其用作参考 以使这个问题变得简单 如果超过 x 像素 则使用 resize 来 getScript jQuery https stackoverflow com questions 11388247 using
  • 记录 mongoose 在应用程序中触发的所有查询

    我有使用nodejs和mongodb的应用程序 我曾使用猫鼬进行ODM 现在我想记录猫鼬在整个应用程序期间触发的所有查询 如何记录这些 您可以像这样启用调试模式 mongoose set debug true 或添加您自己的调试回调 mon
  • 从视觉 API 预览条码扫描仪的尺寸

    我正在使用 Google 的 Android Vision API 中的条形码阅读器示例 预览尺寸似乎没有填满整个可用空间 我使用的是 Nexus 4 预览右侧有一个白色的未使用空间 大约是宽度的 1 3 我希望能够在各种设备上运行这个示例
  • (类型错误:无法在 HttpHeaders.applyUpdate 处读取 null 属性“长度”)Angular 5,Http 客户端

    我在服务中发出 http 请求时收到此响应 这是登录组件 export class LoginComponent credentials Credentials constructor private auth AuthService In
  • Swift 运行时文档 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我一直在探索Apple的swift文档 现在我来这里询问 有关于 Swift 运行时的文档吗 我读过 Swift 编程语言 一书 http
  • 按索引级别为 Pandas Multiindex DataFrame 赋值

    我有一个 Pandas 多索引数据框 我需要为系列中的一列分配值 该系列与数据帧的第一级索引共享其索引 import pandas as pd import numpy as np idx0 np array bar bar bar baz