熊猫:用替代值填充空列

问题描述

我有一个如下的数据框,但有更多行

import pandas as pd
import numpy as np

d = {'col1': ['data1','data2','data3','data4','data5'],'col2': ['a','b','c','d','e']}
df = pd.DataFrame(data=d)

我在此数据框中添加一个空列

df['type']= ' '

现在我想用替代值填充空列。所以如果索引是偶数,那么我想添加'type_a',如果索引是奇数,我想添加'type_b'。

我做了以下

df['type'] = np.where(df.iloc[::2,::2],'type_a','type_b') 

但是索引不匹配,我收到以下错误

ValueError: Length of values does not match length of index

解决方法

试试:

df['type']=np.where(df.index%2==0,'type_a','type_b') 

df 的输出:

    col1    col2    type
0   data1   a       type_a
1   data2   b       type_b
2   data3   c       type_a
3   data4   d       type_b
4   data5   e       type_a