apply函数返回数据帧格式

2024-04-23 08:59:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,一个带有列[a,b,c],另一个带有列[a,b,d],如下所示:

matrix = [(222, 34, 23),
         (333, 31, 11),
         (444, 16, 21),
         (555, 32, 22),
         (666, 33, 27),
         (777, 35, 11)
         ]

# Create a DataFrame object
dfObj = pd.DataFrame(matrix, columns=list('abc'))

print(dfObj)



     a  b   c
0   222 34  23
1   333 31  11
2   444 16  21
3   555 32  22
4   666 33  27
5   777 35  11


matrix = [(222, 34, 5),
         (333, 31, 6),
         (444, 16, 7),
         (555, 32, 8),
         (666, 33, 9),
         (777, 35, 10)
         ]

# Create a DataFrame object
dfObj1 = pd.DataFrame(matrix, columns=list('abd'))

我想用[a,b,c,d]列构造一个新的矩阵,如下所示:

def test_func(x):
    return dfObj1.d[dfObj1['a'].isin([x['a']])]
dfObj['d'] = dfObj.apply(test_func, axis = 1)

但是,dfObj.apply(test_func, axis = 1)的输出是如下所示的数据帧:

    1   2   3   4   5
1   6.0 NaN NaN NaN NaN
2   NaN 7.0 NaN NaN NaN
3   NaN NaN 8.0 NaN NaN
4   NaN NaN NaN 9.0 NaN
5   NaN NaN NaN NaN 10.0

我希望得到以下输出-[6,7,8,9,10]。你知道吗

我知道有几种方法可以实现这个目标,但我只是想找出我在这个方法中做错了什么。你知道吗


Tags: columns数据testdataframeobjectcreatenanmatrix
2条回答

在您的函数中,结果以Series的形式返回,当您为它指定索引do matter时,例如,索引1将返回一个带有索引1的序列,因此它将以矩阵的形式显示在位置上。(apply result将连接,每个输入有不同的索引和列,就像一个小数据帧)

def test_func(x):
    return type(dfObj1.d[dfObj1['a'].isin([x['a']])])
dfObj.apply(test_func, axis = 1)
Out[48]: 
0    <class 'pandas.core.series.Series'>
1    <class 'pandas.core.series.Series'>
2    <class 'pandas.core.series.Series'>
3    <class 'pandas.core.series.Series'>
4    <class 'pandas.core.series.Series'>
5    <class 'pandas.core.series.Series'>
dtype: object

消除索引影响以修复

def test_func(x):
    return dfObj1.d[dfObj1['a'].isin([x['a']])].iloc[0]
dfObj.apply(test_func, axis = 1)
Out[49]: 
0     5
1     6
2     7
3     8
4     9
5    10
dtype: int64

如果在函数中返回带有.values的numpy数组,并在^{}中添加result_type='expand'参数,则有可能:

def test_func(x):
    return  dfObj1.loc[dfObj1['a'].isin([x['a']]), 'd'].values

dfObj['d'] = dfObj.apply(test_func, axis = 1, result_type='expand')
print(dfObj)
     a   b   c   d
0  222  34  23   5
1  333  31  11   6
2  444  16  21   7
3  555  32  22   8
4  666  33  27   9
5  777  35  11  10

如果需要返回缺少值的标量,另一种方法是使用nextiter

def test_func(x):
    return  next(iter(dfObj1.loc[dfObj1['a'].isin([x['a']]), 'd']), np.nan)

dfObj['d'] = dfObj.apply(test_func, axis = 1)

但更好/更快的是使用^{}

dfObj= dfObj.merge(dfObj1[['a','d']], on='a', how='left')
print(dfObj)
     a   b   c   d
0  222  34  23   5
1  333  31  11   6
2  444  16  21   7
3  555  32  22   8
4  666  33  27   9
5  777  35  11  10

^{}

dfObj['d'] = dfObj['a'].map(dfObj1.set_index('a')['d'])
print(dfObj)
     a   b   c   d
0  222  34  23   5
1  333  31  11   6
2  444  16  21   7
3  555  32  22   8
4  666  33  27   9
5  777  35  11  10

相关问题 更多 >