[英]Replacing the corresponding column values in Python Pandas dataframe
I have a data frame, say:我有一个数据框,说:
Name Visits 0 Z 0 1 A 0 2 B 1 3 C 1 4 D 0 5 E 0
Now, I made a list with those names whose visits are 0, so it has Z, A, D, and E. Now, I randomly choose 2 names from these 4. Then, I want to increase the visits of these 2 people by 1. How do I reference only these 2 names, access their corresponding visits and alter it?现在,我列出了那些访问次数为 0 的名字,所以它有 Z、A、D 和 E。现在,我从这 4 个名字中随机选择 2 个名字。然后,我想将这 2 个人的访问次数增加1.如何只引用这两个名字,访问他们对应的访问并修改它? [In python, Pandas] Thank you!
[python,熊猫] 谢谢!
Here is a posible solution:这是一个可能的解决方案:
df.visit[df.visit == 0] += 1
If you already have list of who visited 0 times you can use pd.Series.isin
to create a boolean mask for boolean indexing then increase corresponding values by 1如果您已经有谁访问过 0 次的列表,您可以使用
pd.Series.isin
为 boolean 索引创建一个 boolean 掩码,然后将相应的值增加 1
vals = ['Z', 'A', 'D', 'E']
m = df['Name'].isin(vals)
df.loc[m, 'Visits']+=1
# This only increases Z, A, D, E visits by 1
Try random.choice
from number then assign value by index
尝试
random.choice
from number 然后按index
分配值
df.loc[np.random.choice(df.index[df.Visits==0],2),'Visits'] += 1
df
Out[95]:
Name Visits
0 Z 1
1 A 0
2 B 1
3 C 1
4 D 0
5 E 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.