python - 使用 pandas iterrows 进行字典理解

标签 python pandas dataframe dictionary output

我对使用字典理解的方式的输出有些困惑~

birthday_dict = {data.name: (data.month, data.day) for (index, data) in df_birthday.iterrows()}

给我

{0: (3, 24), 1: (6, 20), 2: (1, 20)}
birthday_dict = {data["name"]: (data.month, data.day) for (index, data) in df_birthday.iterrows()}

给我

{'John': (3, 24), 'Alex': (6, 20), 'Dave': (1, 20)}

我认为 data.name 与 data["name"] 相同,但是当作为键索引插入时它们给出不同的结果。我绝对更喜欢后一种,它使字典更清楚地了解键值给出的生日,但只是想知道键索引中不同输出背后的原因。

感谢您的宝贵时间!

最佳答案

这是因为 df.iterrows 返回 (index, Series) 对,并且这样的 Series 有一个 name属性作为索引:

print(df.iloc[0])

name     John
month       3
day        24
Name: 0, dtype: object

你可以看到有一个Name,当你执行data.name时,它返回的不是该系列的内容(即“John "),但其元数据名称:0

请注意,pandas 在查找内容之前会引用元数据。让我们仔细检查另一个元数据 dtype:

   name  month  day dtype
0  John      3   24  aaaa
1  Alex      6   20  aaaa
2  Dave      1   20  aaaa

{data.name: (data.month, data.day, data.dtype) for (index, data) in df.iterrows()}
# {0: (3, 24, dtype('O')), 1: (6, 20, dtype('O')), 2: (1, 20, dtype('O'))}

话虽这么说,通过属性调用获取项目是危险的(即data.{something}

相反,您应该尝试使用像 data["something"] 这样的索引:

{data["name"]: (data["month"], data["day"], data["dtype"]) for (index, data) in df.iterrows()}

输出:

{'John': (3, 24, 'aaaa'), 'Alex': (6, 20, 'aaaa'), 'Dave': (1, 20, 'aaaa')}

您可以看到 namedtype 现在都来自内容,而不是元数据。

关于python - 使用 pandas iterrows 进行字典理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71596783/

相关文章:

python - 如何将列内容解压到由单元格值确定的新列

python - 对 DataFrame 中各个行的数据求和

r - 将不同列表的子列表组合成数据框列表

r - 通过规则列表动态子集 data.frame

python - 当使用H264编码的MP4文件设置slices=n时,哪里可以查到当前NALU有多少个slice?

python - 按钮未被点击

python - Pandas pivot_table : aggfunc parameter value & quotation marks

python - 这是一个错误还是我不明白什么?

python - 如何生成随机符号并获取他的ascii代码[Python]

python - 使用 Beautiful Soup 解析 HTML 以在 href 之后获取链接