如何通过id从另一个pandas数据帧中的列中获取值

时间:2021-05-04 06:19:14

标签: python pandas dataframe

我有一个 Pandas 数据框 df1 包含 idname 列,另一个数据框 df2 仅包含 id 列,我们如何获取名称df2 中的 df1 id 没有写循环?

target result

附示例代码如下,谢谢!

#!/usr/bin/env python
import numpy as np
import pandas as pd

def add_name_by_id():
    df1 = pd.DataFrame(np.array([[1, 'jack'], [2, 'marry'], [3, 'tom'], [4, 'helen']]),
                       columns=['id', 'name'])
    print(df1)
    df2 = pd.DataFrame(np.array([[1, 4, 20], [2, 2, 30], [2, 3, 30], [3, 3, 25], [
                       3, 2, 25], [4, 4, 35]]), columns=['id', 'hours', 'price'])
    print(df2)

if __name__ == "__main__":
    add_name_by_id()

3 个答案:

答案 0 :(得分:1)

df = pd.merge(left=df1, right=df2, how='inner', on='id')

答案 1 :(得分:1)

您可以使用pandas.DataFrame.merge

df2 = df2.merge(df1, on=['id'])

答案 2 :(得分:1)

首先,我在您的查询中提到了 Reproduced DataFrames (df1) and (df2)。因此,Code 对于 DataFrame Reproduction 如下所述:-

# Import all the Important Libraries
import pandas as pd 

# Reproducing 'DataFrame 1 (df1)'
df1 = pd.DataFrame({
    'id': [1, 2, 3, 4],
    'name': ['jack', 'marry', 'tom', 'helen']
})

# Reproducing 'DataFrame 2 (df2)'
df2 = pd.DataFrame({
    'id': [1, 2, 2, 3, 3, 4],
    'hours': [4, 2, 3, 3, 2, 4],
    'price': [20, 30, 30, 25, 25, 35]
})

# Print Records of 'df1'
df1
# Output of above cell:-
    id  name
0   1   jack
1   2   marry
2   3   tom
3   4   helen
# Print Records of 'df2'
df2
# Output of above cell:-
    id  hours   price
0   1   4       20
1   2   2       30
2   2   3       30
3   3   3       25
4   3   2       25
5   4   4       35

所以,现在我们有了 reproduced 我们的 DataFrames,我们可以朝着我们的 Solution Part 前进。如果你 Analyze 你的 Target Result 那么它只不过是 Merged dataFramedf1df2 基于他们的 id。我们可以将 Tasks 划分为:-

  • Primary Task:- 在 merge
  • 上同时 DataFrame
  • id:- 基于 Secondary Task OR Calculate 值到 Amount Merged dataFrameTarget Result 只不过是 Amount

因此,下面给出了两个场景的 hours * price:-

Code
# Merge both 'DataFrames' for Target Result
target_result = pd.merge(left=df1, right=df2, on='id')

# Calculate 'Amount' for 'Target Result'
target_result['amount'] = target_result['hours']*target_result['price']

# Print 'Target Result'
target_result
<块引用>

要了解有关 # Output of above cell:- id name hours price amount 0 1 jack 4 20 80 1 2 marry 2 30 60 2 2 marry 3 30 90 3 3 tom 3 25 75 4 3 tom 2 25 50 5 4 helen 4 35 140 的更多信息:- Click Here !!!

如您所见,我们已经实现了 pandas.merge()。希望这 Desired Output 对您有所帮助。