[英]How to add a column to a dataframe with a list of row numbers?
我有一個數據框,想要添加一個新的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
獲取列名的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.