【问题标题】:Bug with capital letter label in pandas multi index熊猫多索引中带有大写字母标签的错误
【发布时间】:2018-04-13 21:26:47
【问题描述】:

我在下面的代码中遇到了一个错误。如果我的类别列表的第二个元素是大写字母,那么我的数据框“change_1_month_df”的结果值为 NaN。如果我使用小写字母,则正确插入随机数。有任何想法吗?谢谢

import pandas as pd
import numpy as np

dates = ['d1','d2']
categories = ['a','b']
sub_categories = ['f','g']
my_index = pd.MultiIndex.from_product([categories,sub_categories])
change_1_month_df = pd.DataFrame(index=my_index,columns=dates)

for a in categories:
    for d in dates:
        print a,d
        if a == 'W':
            None
        else:
            change_1_month_df.ix[a].ix['f'][d] = np.random.randn(1)
            change_1_month_df.ix[a].ix['g'][d] = np.random.randn(1)

change_1_month_df

【问题讨论】:

  • .ix 不推荐使用 iloc
  • 谢谢,.loc 问题依然存在
  • 是的,我使用的是 2.7

标签: python pandas


【解决方案1】:

你可以试试这个吗?通过使用.loc 选择多索引

for a in categories:
    for d in dates:

        if a == 'W':
            None
        else:
            change_1_month_df.loc[(a, 'f'), d]=np.random.randn(1)[0]
            change_1_month_df.loc[(a, 'g'), d]=np.random.randn(1)[0]

change_1_month_df

【讨论】:

  • 文,你说得对,它与 .loc 或 .ix 的链接有关,在内存中创建了一个副本,而不是将其分配给原始数据帧。
  • 是的,这就是答案。我没有发布这个,因为我不知道为什么原始方法返回 NaN。
  • @cᴏʟᴅsᴘᴇᴇᴅ 对于他的方法,它对我有用,只需返回警告 .ix 。
  • 有趣...如果我将b 更改为B,它就不再起作用了。
  • 自从我发表了评论后,我就像我必须回应一样填写。而且,我不知道。但是,不建议这样做。 See these docs
猜你喜欢
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 2015-01-20
  • 1970-01-01
  • 2021-10-16
  • 2016-10-16
  • 2019-01-19
  • 2016-09-23
相关资源
最近更新 更多