通过应用来自第二个datafram的规则来更改dataframe

2024-09-25 00:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有两个数据帧。在

输入数据框架:-在

id   number      idsc                 mfd 
738  as6812      *fage abc van brw    amz 
745  786-151     *glaeceau smt sp     amz 
759  b0nadum     ankush 574415 mo...  admz 
764  fdad3-al-c  lib anvest-al...     amz 
887  rec-2s-5    or abc sur...        c 
64   00954       ankush pure g...     amz 
8    0000686     dor must die         a 
3    000adf623   bsc test 10-pi...    amz 

检查条件数据框架:-在

^{pr2}$

我正在寻找应用每一个规则条件数据帧输入数据帧,并获得一个新的数据帧。在

如果我的条件是真的,那么我需要对所有行应用它。如果除true之外还有任何特定值,那么我需要对特定记录应用该条件。在

在pyspark中有没有更好的方法来实现这一点,因为正则表达式与python相关。而不是在for循环中运行它。在

id   number     idsc              mfd 
738  as6812     *fage a van brw   amz 
745  786-151    *glaeceau smt sp  amz 
759  b0nadum    ank 574415 mo...  admz 
764  fdad3-al-c lib anvest-al...  amz 
887  rec-2s-5   or a sur...       c 
64   00954      ank pure g...     amz 
8    0000686    dor must die      a 
3    000adf623  bsc test 10-pi... amz 

输入数据管道分离

id| number|idsc|mfd 
738|as6812|*fage abc van brw|amz 
745|786-151|*glaeceau smt sp|amz 
759|b0nadum|ankush 574415 mo...|admz 
764|fdad3-al-c|lib anvest-al...|amz 
887|rec-2s-5|or abc sur...|c 
64| 00954|ankush pure g...|amz 
8|0000686|dor must die a 
3|000adf623|bsc test 10-pi...|amz 

分离条件数据管道

条件|目标字段|表达式| b|id |

True|idsc|[idsc].lower()|1 
[mfd]=="amz"|idsc|re.sub(r'\abc\b','a',[idsc])|1 
[mfd]=="admz"|idsc|re.sub(r'and \d+ other item', '', [idsc])|1 
True|idsc|re.sub(r'[^a-z0-9 ]',r'',[idsc])|1 
True|idsc|[idsc].strip()|1 
[mfd] == "c"|idsc|re.sub(r'\ankush\b','ank',[idsc])|1 
True|number|re.sub(r'[^0-9]',r'',[number])|1
True|number|[number].strip()|1 

谢谢, 安库什·雷迪


Tags: 数据reidtruenumber条件alabc
1条回答
网友
1楼 · 发布于 2024-09-25 00:35:54

您可以尝试使您的条件数据帧可求值。在

如果它是可计算的,则可以对条件和表达式调用eval()。在

def apply_condition(df, df_condition):
 # write a function get_df_evaluable_condition which both does
 # replace "[any_column]" by "df.['any_column']" in createcondition
 # replace "[destinationfield]" by "element" in expression

 df_evaluable_condition = get_df_evaluable_condition(df_evaluable_condition)

 for index, row in df_evaluable_condition.iterrows():
    createcondition = row['createcondition']
    destinationfield = row['destinationfield']
    expression = row['expression']
    # just apply expression where createcondition is true
    df.loc[eval(createcondition), destinationfield] = 
      df.loc[eval(createcondition), destinationfield].apply(lambda element: eval(expression))

顺便说一下,如果表达式包含对不是目标列的列的引用,则最后一行代码将不起作用。你需要更复杂的东西来实现你想要的。在

我不建议使用这种方法,如果你不知道你的条件数据帧是什么样子。不要对未知字符串调用eval()!在

相关问题 更多 >