如何用其他数据框中的ID替换数据框中的2列值?

时间:2019-12-10 13:32:00

标签: python pandas

有一个df_value:

metric_type metric_name   metric_value  
visits      total         111
visits      time_related  222
followers   total         333
followers   time_related  444

和另一个具有metric_type和metric_name的ID的df

df_ids

metric_id  metric_name   metric_type 
1          total         visits
2          time_related  visits
3          total         followers   
4          time_related  followers   

我需要这样更改值:

metric_id   metric_value    
1           111
2           222
3           333
4           444

我试图在两个df的一列中结合metric_name和metric_type:

df_value['combined']=df_value.apply(lambda x:'%s_%s' % (x['metric_name'],x['metric_type']),axis=1)
df_ids['combined']=df_ids.apply(lambda x:'%s_%s' % (x['metric_name'],x['metric_type']),axis=1)

并尝试更改此类值

df_value.rename(
                columns=dict(zip(df_ids['combined'], df_ids['metric_id'])))

但是它不起作用,我不知道如何进行。感谢任何帮助

2 个答案:

答案 0 :(得分:2)

这应该有效:

df = pd.DataFrame(data = [df_ids['metric_id'], df_value['metric_value']]).transpose()

输出:

   metric_id  metric_value
0          1           111
1          2           222
2          3           333
3          4           444

答案 1 :(得分:1)

我想这就是你想要的:

# Dataframes:
data1 = [
    ['visits', 'total', 111],
    ['visits', 'time_related', 222],
    ['followers', 'total', 333],
    ['followers', 'time_related', 444]
]
cols_1 = ['metric_type', 'metric_name', 'metric_value']

df1 = pd.DataFrame(data1, columns=cols_1)

data2 = [
    [1, 'total', 'visits'],
    [2, 'time_related', 'visits'],
    [3, 'total', 'followers'],
    [4, 'time_related', 'followers']
]
cols_2 = ['metric_id', 'metric_name', 'metric_type']

df2 = pd.DataFrame(data2, columns=cols_2)

# Solution:
pd.merge(
    df1, df2, on=['metric_type', 'metric_name']
)[['metric_id', 'metric_value']]

输出:

  metric_id   metric_value
0   1         111
1   2         222
2   3         333
3   4         444