python - 用 Pandas 替换另一个数据框中数据框中的值

标签 python pandas dataframe replace

我有 3 个数据帧:df1df2df3。我试图用 df2 中包含的一些值填充 df1NaN 值。从 df2 中选择的值也是根据一个简单函数 (mul_val) 的输出来选择的,该函数处理存储在 df3 中的一些数据。

我能够得到这样的结果,但我想以更简单、更容易的方式和更具可读性的代码找到。

这是我目前所拥有的:

import pandas as pd
import numpy as np

# simple function
def mul_val(a,b):
    return a*b

# dataframe 1
data = {'Name':['PINO','PALO','TNCO' ,'TNTO','CUCO' ,'FIGO','ONGF','LABO'],
        'Id'  :[  10  ,  9   ,np.nan ,  14   , 3    ,np.nan,  7   ,np.nan]}
df1 = pd.DataFrame(data)

# dataframe 2
infos = {'Info_a':[10,20,30,40,70,80,90,50,60,80,40,50,20,30,15,11],
         'Info_b':[10,30,30,60,10,85,99,50,70,20,30,50,20,40,16,17]}
df2 = pd.DataFrame(infos)

dic = {'Name': {0: 'FIGO', 1: 'TNCO'}, 
       'index': {0: [5, 6], 1: [11, 12, 13]}}
df3 = pd.DataFrame(dic)

#---------------Modify from here in the most efficient way!-----------------

for idx,row in df3.iterrows():
    store_val = []
    print(row['Name'])
    for j in row['index']:
        store_val.append([mul_val(df2['Info_a'][j],df2['Info_b'][j]),j])
    store_val = np.asarray(store_val)

    # - Identify which is the index of minimum value of the first column
    indx_min_val = np.argmin(store_val[:,0])

    # - Get the value relative number contained in the second column
    col_value = row['index'][indx_min_val]

    # Identify value to be replaced in df1
    value_to_be_replaced = df1['Id'][df1['Name']==row['Name']]

    # - Replace such value into the df1 having the same row['Name']
    df1['Id'].replace(to_replace=value_to_be_replaced,value=col_value, inplace=True)

通过在每次迭代时打印 store_val 我得到:

FIGO
[[6800    5]   
 [8910    6]]
TNCO
[[2500   11]
 [ 400   12]
 [1200   13]]

让我们做一个简单的例子:考虑到 FIGO,我将 6800 确定为 68008910 之间的最小数字>。因此,我选择了放在 df1 中的数字 5。对 df3 的剩余行重复这样的操作(在这种情况下我只有 2 行但它们可能更多),最终结果应该是这样的:

In[0]: before           In[0]: after
Out[0]:                 Out[0]: 
     Id  Name                Id  Name
0  10.0  PINO           0  10.0  PINO
1   9.0  PALO           1   9.0  PALO
2   NaN  TNCO  ----->   2  12.0  TNCO
3  14.0  TNTO           3  14.0  TNTO
4   3.0  CUCO           4   3.0  CUCO
5   NaN  FIGO  ----->   5   5.0  FIGO
6   7.0  ONGF           6   7.0  ONGF
7   NaN  LABO           7   NaN  LABO

注意:如果需要,您还可以删除 for 循环并使用不同类型的格式来存储数据(列表、数组...);重要的是最终结果仍然是一个数据框。

最佳答案

我可以提供两个类似的选项,它们可以在几行中实现与您的循环相同的结果:

1.使用 apply 和 fillna()(fillnacombine_first 快两倍):

  df3['Id'] = df3.apply(lambda row: (df2.Info_a*df2.Info_b).loc[row['index']].argmin(), axis=1)
  df1 = df1.set_index('Name').fillna(df3.set_index('Name')).reset_index()

2.使用函数(lambda不支持赋值,所以你必须申请一个func)

def f(row):
    df1.ix[df1.Name==row['Name'], 'Id'] = (df2.Info_a*df2.Info_b).loc[row['index']].argmin()
df3.apply(f, axis=1)

或不依赖于全局定义的轻微变体:

def f(row, df1, df2):
    df1.ix[df1.Name==row['Name'], 'Id'] = (df2.Info_a*df2.Info_b).loc[row['index']].argmin()
df3.apply(f, args=(df1,df2,), axis=1)

请注意,尽管您的解决方案更加冗长,但对于这个小型数据集,您的解决方案将花费最少的时间(7.5 毫秒对我的两个 9.5 毫秒)。速度相似是有道理的,因为在这两种情况下,都是在 df3

的行上循环的问题

关于python - 用 Pandas 替换另一个数据框中数据框中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40784770/

相关文章:

python - 向用户读取文档行(python)

java - Pig 将制表符 (\t) 作为动态 CSV 解析的参数

python - 如何在 df.iterrows() 期间删除 Pandas 数据框中的当前行

python - 根据现有变量创建新变量时遇到问题

python - 如何在DataFrame中有条件地获取列的前n个值的列表?

r - 使用相同的引用比较组内的日期

python - 为什么 mydict.items().sort() 不起作用?

python - 属性错误位于/admin/student/student_record/

python - 如何重新配置​​ pandas 数据框?

r - 如何在r中导入csv数据后删除空行