Python Pandas - 根据索引替换值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37725195/
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-08-19 19:51:48  来源:igfitidea点击:

Pandas - Replace values based on index

pythonnumpypandasreplacedataframe

提问by Colin O'Brien

Apologies if this has been asked before, I can't seem to find an answer.

抱歉,如果之前有人问过这个问题,我似乎找不到答案。

If I create a dataframe like so:

如果我像这样创建一个数据框:

import pandas as pd, numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=list('AB'))

How would I change the entry in column A to be the number 16 from row 0 -15, for example? In other words, how do I replace cells based purely on index?

例如,如何将 A 列中的条目更改为第 0 -15 行的数字 16?换句话说,如何完全根据索引替换单元格?

回答by jezrael

Use loc:

使用loc

df.loc[0:15,'A'] = 16
print (df)
     A   B
0   16  45
1   16   5
2   16  97
3   16  58
4   16  26
5   16  87
6   16  51
7   16  17
8   16  39
9   16  73
10  16  94
11  16  69
12  16  57
13  16  24
14  16  43
15  16  77
16  41   0
17   3  21
18   0  98
19  45  39
20  66  62
21   8  53
22  69  47
23  48  53

Solution with ixis deprecated.

解决方案与ix弃用

回答by amandeep1991

One more solution is

另一种解决方案是

df.at[0:15, 'A']=16

print(df.head(20))

OUTPUT:

输出

     A   B
0   16  44
1   16  86
2   16  97
3   16  79
4   16  94
5   16  24
6   16  88
7   16  43
8   16  64
9   16  39
10  16  84
11  16  42
12  16   8
13  16  72
14  16  23
15  16  28
16  18  11
17  76  15
18  12  38
19  91   6

回答by nischi

In addition to the other answers, here is what you can do if you have a list of individual indices:

除了其他答案之外,如果您有单个索引列表,您可以执行以下操作:

indices = [0,1,3,6,10,15]
df.loc[indices,'A'] = 16

print(df.head(16))

Output:

输出:

     A  B
0   16  4
1   16  4
2    4  3
3   16  4
4    1  1
5    3  0
6   16  4
7    2  1
8    4  4
9    3  4
10  16  0
11   3  1
12   4  2
13   2  2
14   2  1
15  16  1