类型错误:字符串索引必须是整数 Python Pandas

时间:2021-07-11 04:30:17

标签: python pandas dataframe

这是我的 Pandas 数据框

#df1:

  col1  col2    col3
0   a   1.0     1.0
1   a   2.0     2.0
2   b   3.0     3.0
3   b   NaN     4.0
4   a   5.0     5.0

我正在尝试编写一个函数来获取基于 col2>2 的行:

def colreturn(datarow):
    if datarow['col2']>2:
        return datarow['col2']
    else:
        return ''

它正在抛出错误:

TypeError: string indices must be integers

但是,我可以在数据帧本身中做到这一点:

df1['col2'] = np.where(df1['col2']>1, df1['col2'], '')
df1

请帮忙。

0 个答案:

没有答案