我有一个dataframe,想添加一个新的bool值列,引用一个行号列表。

>>> df
    col1  col2
0     1     1
1     2     2
2     4     3
3     8     4

>>> lst_rowNumbers
[1, 3]

结果如下:
    col1  col2   bool
0     1     1  False
1     2     2   True
2     4     3  False
3     8     4   True

我原以为这能行,但没用。
>>> df['bool'] = False
>>> df.iloc[ lst_rowNumbers ]['bool'] = True

我怎么处理熊猫?

最佳答案

如果要按索引名称选择:

df['bool'] = False
df.loc[ lst_rowNumbers , 'bool'] = True

或:
df['bool'] = df.index.isin(lst_rowNumbers)

print (df)
   col1  col2   bool
0     1     1  False
1     2     2   True
2     4     3  False
3     8     4   True

如果需要按位置选择,则按Index.get_loc获取列名的位置:
print (df)
   col1  col2
a     1     1
b     2     2
c     4     3
d     8     4

lst_rowNumbers = [1,3]
df['bool'] = False
df.iloc[ lst_rowNumbers , df.columns.get_loc('bool')] = True

或使用isin索引返回的实际索引值:
df['bool'] = df.index.isin(df.index[lst_rowNumbers])

print (df)
   col1  col2   bool
a     1     1  False
b     2     2   True
c     4     3  False
d     8     4   True

关于python - 如何在具有行号列表的数据框中添加一列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54061339/

10-11 07:37