gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:47 25 4
gpt4 key购买 nike

有一个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

我尝试在两个 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

关于python - 如何用其他数据框中的 id 替换数据框中的 2 列值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59268389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com