Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 条件合并熊猫_Pandas - Fatal编程技术网

Pandas 条件合并熊猫

Pandas 条件合并熊猫,pandas,Pandas,我希望执行条件合并,下面是名为df的数据帧。我希望合并引用df_reference和df over weight。 合并应使权重等于或小于。 示例:第1行的权重为62.2,需要与权重60合并 import pandas as pd import io data = """ name weight Arash 62.2 Bash 98.2 Kim 88.2 Dim 92.1 Ghst 63.2 """

我希望执行条件合并,下面是名为df的数据帧。我希望合并引用df_reference和df over weight。 合并应使权重等于或小于。 示例:第1行的权重为62.2,需要与权重60合并

import pandas as pd
import io

data = """
name    weight
Arash   62.2
Bash    98.2
Kim     88.2
Dim     92.1
Ghst    63.2
"""

df = pd.read_table(io.StringIO(data), delim_whitespace=True)
参考表

reference = """
weight  performance
60   100
65    95
70    93
75    92
80    90
85    85
90    79
95    75
"""

df_reference = pd.read_table(io.StringIO(reference), delim_whitespace=True)
以下是预期输出:

output = """
name    weight   weight_l    performance_l
Arash   62.2       60           100       
Bash    91.2       90           79       
Kim     88.2       85           85      
Dim     92.1       90           95
Ghst    63.2       60           65      
"""

df_expectation = pd.read_table(io.StringIO(output), delim_whitespace=True)
当存在精确匹配时,我可以合并,但当匹配不相等时无法合并。

请尝试此代码

df_reference.columns = ['weight_l', 'performance_l']
df['weight_l'] = df['weight'] // 10 * 10
df.loc[df['weight'] % 10 > 5, 'weight_l'] = df.loc[df['weight'] % 10 > 5, 'weight_l'] + 5
df_expectation = pd.merge(df,df_reference, on=['weight_l'])