简体   繁体   English

使用非唯一索引在Pandas DataFrame中查找和更新行

[英]Find and update row in Pandas DataFrame with non-unique index

I have a pandas DataFrame with a non-unique index, and I need to update one of the rows. 我有一个带有非唯一索引的pandas DataFrame,我需要更新其中一行。 I am able to update the row if I can index it numerically, as below: 如果我可以用数字索引它,我可以更新该行,如下所示:

array = np.random.randint(1, 10, (3, 3))
df = pd.DataFrame(array, index=['one', 'one', 'two'], columns=['col1', 'col2', 'col3'])

# df looks like this:
#        col1   col2    col3
#one        2       3       6
#one        3       1       5
#two        4       5       2


new_data = pd.Series({'col1': 'new', 'col2': 'new', 'col3': 'new'})
df.iloc[0] = new_data

But what if I don't know the row number? 但如果我不知道行号怎么办? Let's say I just want to set the first row with an index of 'one'. 假设我只想设置索引为“1”的第一行。 So, I want to find the slice using .loc and then assign my new value to the first row. 所以,我想使用.loc找到切片,然后将我的新值分配给第一行。

new_data = pd.Series({'col1': 'new', 'col2': 'new', 'col3': 'new'})
df.loc['one'][0] = new_data

However, this is assignment using chained indexing, which is not so good. 但是,这是使用链式索引的分配,这不是那么好。 Is there a different way to do this? 有没有不同的方法来做到这一点?

You can access it with df.iloc[(df.index == 'one').argmax()] . 您可以使用df.iloc[(df.index == 'one').argmax()]访问它。

So your assignment would look like: 所以你的任务看起来像:

df.iloc[(df.index == 'one').argmax()] = new_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM