[英]How to update a column value in a row for specific value in another column in pandas dataframe?
I have a dataframe with 3 columns id
, type
, type_value
.我有一个包含 3 列id
、 type
、 type_value
的数据type_value
。
They're already populated with values.它们已经填充了值。 type
column contains repeating values type1
, type2
, type3
, type4
. type
列包含重复值type1
, type2
, type3
, type4
。
type_value
contains a Counter object which has frequencies of occurrences in it. type_value
包含一个 Counter 对象,该对象具有出现频率。
All I need is to perform some operations on the Counter dictionary and update the type_value
column when the type
is matched with type1
and leave the other rows untouched.我所需要的只是对 Counter 字典执行一些操作,并在type
与type1
匹配时更新type_value
列,并保持其他行不变。
Input:输入:
id type type_value
1 type1 Counter object that needs to be updated
2 type2 some random value
3 type3 some random value
4 type4 some random value
5 type1 Counter object that needs to be updated
6 type2 some random value
7 type3 some random value
8 type4 some random value
9 type1 Counter object that needs to be updated
10 type2 some random value
11 type3 some random value
12 type4 some random value
13 type1 Counter object that needs to be updated
14 type2 some random value
15 type3 some random value
16 type4 some random value
Output:输出:
id type type_value
1 type1 Do an operation on this and update with new values
2 type2 some random value
3 type3 some random value
4 type4 some random value
5 type1 Do an operation on this and update with new values
6 type2 some random value
7 type3 some random value
8 type4 some random value
9 type1 Do an operation on this and update with new values
10 type2 some random value
11 type3 some random value
12 type4 some random value
13 type1 Do an operation on this and update with new values
14 type2 some random value
15 type3 some random value
16 type4 some random value
Fitler rows by condition and apply your custom function: Fitler 按条件行并应用您的自定义函数:
def func(x):
#your operation
return x
mask = df['type'] == 'type1'
df.loc[mask, 'type_value'] = df.loc[mask, 'type_value'].apply(func)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.