如何使用multiindex为现有系列赋值?

时间:2017-11-21 12:39:35

标签: python pandas indexing

我有Series如下:

In [1]: import pandas as pd

In [2]: index = pd.MultiIndex.from_product([['A', 'B'], ['x', 'y']], names=['u', 'v'])

In [3]: ser = pd.Series(range(4), index=index)

In [4]: ser
Out[4]: 
u  v
A  x    0
   y    1
B  x    2
   y    3
dtype: int64

我想更改现有Series的前两个值,索引为['x', 'y']

In [5]: ser.loc['A'] = pd.Series([100, 202], index=['x', 'y'])

In [6]: ser
Out[6]: 
u  v
A  x    NaN
   y    NaN
B  x    2.0
   y    3.0
dtype: float64

In [7]: pd.__version__
Out[7]: u'0.21.0'

但结果出乎我的意料。解决这个问题的正确方法是什么?

修改 @jezrael的解决方案有效。然而,这让我非常困惑。由于ser.loc['A']ser['A']似乎相同。我错过了什么吗?

In [7]: ser['A']
Out[7]: 
v
x    100
y    202
dtype: int64

In [8]: ser.loc['A']
Out[8]: 
v
x    100
y    202
dtype: int64

1 个答案:

答案 0 :(得分:1)

仅限MutliIndex Series 0.21.0中的mux = pd.MultiIndex.from_product([['aaa'], ['x', 'y']]) ser.loc['A'] = pd.Series([100, 202], index=mux) print (ser) u v A x 100 y 202 B x 2 y 3 dtype: int64 工作集:

ser['A'] = pd.Series([100, 202], index=['x', 'y'])

来自comment of Michał Politowski的工作解决方案:

 public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int TYPE_FIRST_ITEM = 0;
    public static final int TYPE_ITEM = 1;

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case TYPE_FIRST_ITEM:
                final View view = inflater.inflate(R.layout.big_item, parent, false);
                return new BigViewHolder(view);
            case TYPE_ITEM:
                final View view2 = inflater.inflate(R.layout.normal_item, parent, false);
                return new NormalViewHolder(view2);
            default:
                return null;
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (holder.getItemViewType()) {
            case TYPE_FIRST_ITEM:
                BigViewHolder bigViewHolder = (BigViewHolder) holder;
                // Do what you need for the first item
                break;
            case TYPE_ITEM:
                NormalViewHolder normalViewHolder = (NormalViewHolder) holder;
                // Do what you for the other items
                break;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_FIRST_ITEM;
        } else return TYPE_ITEM;
    }

    final class NormalViewHolder extends RecyclerView.ViewHolder {
        public NormalViewHolder(View itemView) {
            super(itemView);
        }
        // find your views here
    }

    final class BigViewHolder extends RecyclerView.ViewHolder {
        public BigViewHolder(View itemView) {
            super(itemView);
        }
        // find your views here
    }
}