如何更新dataframe行比较来自另一个datafram的数据

2024-04-26 23:17:32 发布

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

df1
    antecedent  consequent  p
0   [5] [1] 1.0
1   [3] [1, 5, 4,]  1.0

    nodealarm   count1  nodealarmrank1
0   test1   110 1
1   test2   201 2
2   test3   300 3
3   test4   600 4
4   test100 60  5

输出

df1
    antecedent  consequent  p
0   [test100]   [test1]  1.0
1   [test3]   [test1,test100,test4] 1.0

Tags: df1test1test2test3test4count1consequentantecedent
1条回答
网友
1楼 · 发布于 2024-04-26 23:17:32

在列上创建字典^{}^{}

d =dict(df2[['nodealarmrank1','nodealarm']].values)

df1['antecedent'] = df1['antecedent'].apply(lambda x: list(map(d.get,x)))
df1['consequent'] = df1['consequent'].apply(lambda x: list(map(d.get,x)))

df1
    antecedent  consequent              p
0   [test100]   [test1]                 1
1   [test3]     [test1, test100, test4] 1

或者使用for循环和^{}

for column in ['antecedent','consequent']:
    df1.update(df1[column].apply(lambda x: list(map(d.get,x))))

for column in ['antecedent','consequent']:
    df1[column] = df1[column].apply(lambda x: list(map(d.get,x)))

设置
数据帧1:

df1 = pd.DataFrame({'antecedent':[[5],[3]],'consequent':[[1],[1, 5, 4,]],'p':[1,1]})
df1

    antecedent  consequent  p
0   [5]         [1]         1
1   [3]         [1, 5, 4]   1

数据帧2:

df2 = pd.DataFrame({'nodealarm':['test1','test2','test3','test4','test100'],'count1':[110,201,300,600,60],'nodealarmrank1':[1,2,3,4,5]})
df2

    nodealarm   count1  nodealarmrank1
0   test1       110     1
1   test2       201     2
2   test3       300     3
3   test4       600     4
4   test100     60      5

相关问题 更多 >