熊猫:用替代值填充空列

扎拉科拉加尔

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章