python series增加一行_在MultiIndex DataFrame / Series中添加一行

这篇博客探讨了如何在具有MultiIndex的DataFrame或Series中添加一行数据。通过示例展示了使用`.ix`或`.loc`时可能出现的问题及解决方法,指出必须完全指定所有轴来使多级索引工作。同时,建议使用重新索引或拼接/追加新DataFrame作为更简便的替代方案,特别是当需要添加的数据量较小时。
摘要由CSDN通过智能技术生成

I was wondering if there is an equivalent way to add a row to a Series or DataFrame with a MultiIndex as there is with a single index, i.e. using .ix or .loc?

I thought the natural way would be something like

row_to_add = pd.MultiIndex.from_tuples()

df.ix[row_to_add] = my_row

but that raises a KeyError. I know I can use .append(), but I would find it much neater to use .ix[] or .loc[].

here an example:

>>> df = pd.DataFrame({'Time': [dt.datetime(2013,2,3,9,0,1), dt.datetime(2013,2,3,9,0,1)], 'hsec': [1,25], 'vals': [45,46]})

>>> df

Time hsec vals

0 2013-02-03 09:00:01 1 45

1 2013-02-03 09:00:01 25 46

[2 rows x 3 columns]

>>> df.set_index(['Time','hsec'],inplace=True)

>>> ind = pd.MultiIndex.from_tuples([(dt.datetime(2013,2,3,9,0,2),0)],names=['Time','hsec'])

>>> df.ix[ind] = 5

Traceback (most recent call last):

File "", line 1, in

df.ix[ind] = 5

File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 96, in __setitem__

indexer = self._convert_to_indexer(key, is_setter=True)

File "C:\Program Files\Python27\lib\site-packages\pandas\core\indexing.py", line 967, in _convert_to_indexer

raise KeyError('%s not in index' % objarr[mask])

KeyError: "[(Timestamp('2013-02-03 09:00:02', tz=None), 0L)] not in index"

解决方案

You have to specify a tuple for the multi-indexing to work (AND you have to fully specify all axes, e.g. the : is necessary)

In [26]: df.ix[(dt.datetime(2013,2,3,9,0,2),0),:] = 5

In [27]: df

Out[27]:

vals

Time hsec

2013-02-03 09:00:01 1 45

25 46

2013-02-03 09:00:02 0 5

Easier to reindex and/or concat/append a new dataframe though. Generally setting (with this kind of enlargement), only makes sense if you are doing it with a small number of values. As this makes a copy when you do this.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值