简体   繁体   English

如何基于另一列的值应用熊猫函数?

[英]How to apply a pandas function based on the value of another column?

I have a pandas dataframe with two columns, one with some string values and another one with empty dicts: 我有一个两列的pandas数据框,一列有一些字符串值,另一列有空dict:

ColA ColB
True  {}
False {}
True  {}
True  {}
False {}
False {}
True  {}

I have a function that updates a dict with some other values: 我有一个函数,可以使用其他一些值更新字典:

def update_dict(a):
    return a.update({"VAL":["yes"]})

How can I apply the above function to all the ColB cells that have "False" strings next to them in their ColA?: 如何将上述功能应用于在ColA旁边带有“假”字符串的所有ColB单元?

ColA ColB
True  {}
False {"VAL":["yes"]}
True  {}
True  {}
False {"VAL":["yes"]}
False {"VAL":["yes"]}
True  {}

I know that in pandas you can use the apply function or applymap. 我知道在熊猫中您可以使用apply函数或applymap。 However, I do not know how can I do it based on a previous column value. 但是,我不知道如何基于上一列的值来执行此操作。

It is possible but working with dict in values of columns is not recommended, because lost all vectorized functions: 有可能,但是不建议在列的值中使用dict ,因为会丢失所有矢量化函数:

def update_dict(a):
    a.update({"VAL":["yes"]})
    return a

df['ColB'] = [update_dict(j) if i == 'False' else j for i, j in zip(df['ColA'], df['ColB'])]
print (df)
    ColA              ColB
0   True                {}
1  False  {'VAL': ['yes']}
2   True                {}
3   True                {}
4  False  {'VAL': ['yes']}
5  False  {'VAL': ['yes']}
6   True                {}

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

相关问题 如何根据另一列中的值将函数应用于Pandas中的列? - How to apply a function to a column in Pandas depending on the value in another column? Pandas根据另一列中的值应用基于值的值 - Pandas apply based value based on value in another column 如何根据另一列的值将 function 应用于多列? - How to apply function to multiple columns based on value of another column? 熊猫根据另一列将条件应用于列值 - pandas apply condition to column value based on another column 如何基于一列对 df 进行分组并将函数应用于熊猫中的另一列 - How to group a df based on one column and apply a function to another column in pandas Pandas数据帧根据其他列值将函数应用于列字符串 - Pandas dataframe apply function to column strings based on other column value 基于另一列对熊猫数据框应用不同的功能 - Apply different function to pandas dataframe based on another column 根据熊猫中另一列的值在groupby之后应用lambda函数 - apply lambda function after groupby based on values of another column in pandas 根据特定列中的值将函数应用于熊猫中的数据框行 - Apply function to dataframe row in pandas based on value in specific column 如何将正则表达式应用于大熊猫中的列以查找值,然后对此应用函数? - How to apply regex to a column in pandas to find a value and then apply a function to this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM