Python 如何用来自其他数据帧的ID替换数据帧中的2列值?
有一个df_值:Python 如何用来自其他数据帧的ID替换数据帧中的2列值?,python,pandas,Python,Pandas,有一个df_值: metric_type metric_name metric_value visits total 111 visits time_related 222 followers total 333 followers time_related 444 和另一个df,其中id表示度量值类型和度量值名称 df_ids metric_id metric_name metric_type 1
metric_type metric_name metric_value
visits total 111
visits time_related 222
followers total 333
followers time_related 444
和另一个df,其中id表示度量值类型和度量值名称
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
我已尝试在两个dfs中的一列中组合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'])))
但它不起作用,我不知道如何继续。感谢您的帮助我想这就是您想要的:
# 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
metric_id metric_value
0 1 111
1 2 222
2 3 333
3 4 444
这应该奏效:
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
metric_id metric_value
0 1 111
1 2 222
2 3 333
3 4 444
这些是实际值,其中1->1112->222。。。9->999它可以是任何值,1->15653等等。你能手动编写你想要的输出吗?把它放好,我需要这样更改值:df_value.mergedf_id,on=['metric_name','metric_type']?