Pandas:如何根据 id 列表增加列的单元格值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39458871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:59:59  来源:igfitidea点击:

Pandas: how to increment a column's cell value based on a list of ids

pythonpandasdataframe

提问by AlanH

I have a list of ids that correspond to the row of a data frame. From that list of ids, I want to increment a value of another column that intersects with that id's row.

我有一个对应于数据框行的 id 列表。从该 id 列表中,我想增加与该 id 行相交的另一列的值。

What I was thinking was something like this:

我的想法是这样的:

ids = [1,2,3,4]

for id in ids:
    my_df.loc[my_df['id']] == id]['other_column'] += 1

But this doesn't work. How can I mutate the original df, my_df?

但这不起作用。我怎样才能改变原来的 df, my_df

回答by MaxU

try this:

尝试这个:

my_df.loc[my_df['id'].isin(ids), 'other_column'] += 1

Demo:

演示:

In [233]: ids=[0,2]

In [234]: df = pd.DataFrame(np.random.randint(0,3, (5, 3)), columns=list('abc'))

In [235]: df
Out[235]:
   a  b  c
0  2  2  1
1  1  0  2
2  2  2  0
3  0  2  1
4  0  1  2

In [236]: df.loc[df.a.isin(ids), 'c'] += 100

In [237]: df
Out[237]:
   a  b    c
0  2  2  101
1  1  0    2
2  2  2  100
3  0  2  101
4  0  1  102

回答by NickBraunagel

the ids are unique, correct? If so, you can directly place the idinto the df:

id 是唯一的,对吗?如果是这样,您可以直接将id放入df

ids = [1,2,3,4]

for id in ids:
    df.loc[id,'column_name'] = id+1