写清单理解

时间:2017-03-20 23:57:29

标签: python pandas

我对Python很新,并试图提高我对列表推导的理解。

我想将下面的for循环转换为列表理解。我的努力失败,出现了一条我无法破译的错误消息: IndexError: ('index 17 is out of bounds for axis 1 with size 3', 'occurred at index 0')

代码:

# 1: Original Code With For Loop (Working)
import pandas as pd
import numpy as np

A = pd.DataFrame([2,20], index=['b','a'])
B = pd.DataFrame([3,4,5], index=['a','b','c'])
C= A-B
print(C)

for x in range(3):
    if ~np.isnan(C.iloc[x][0]):
        C.iloc[x] = C.iloc[x][0]
    else:
        C.iloc[x] = B.iloc[x][0]
print(C)


# 2: New Code Incorporating List Comprehension (Not Working)
A = pd.DataFrame([2,20], index=['b','a'])
B = pd.DataFrame([3,4,5], index=['a','b','c'])
C= A-B
print(C)

C.apply(lambda x: C.iloc[x][0] if ~np.isnan(C.iloc[x][0]) else B.iloc[x][0])

2 个答案:

答案 0 :(得分:3)

这就是你想要的吗?

In [177]: A.sub(B).fillna(B)
Out[177]:
      0
a  17.0
b  -2.0
c   5.0

或者这个:

In [178]: A.sub(B, fill_value=0)
Out[178]:
      0
a  17.0
b  -2.0
c  -5.0

另一个熊猫解决方案:

In [193]: C
Out[193]:
      0
a  17.0
b  -2.0
c   NaN

In [194]: C.where(C.notnull(), B)
Out[194]:
      0
a  17.0
b  -2.0
c   5.0

答案 1 :(得分:2)

for x in range(3):
    if ~np.isnan(C.iloc[x][0]):
        C.iloc[x] = C.iloc[x][0]
    else:
        C.iloc[x] = B.iloc[x][0]

列表理解将是

[C.iloc[x][0] if ~np.isnan(C.iloc[x][0]) else B.iloc[x][0]
    for x in range(3) ]

然后,您需要将结果列表分配给适当的变量。我无法做到这一点,因为您没有包含足够的代码来测试您的上下文中的结果。

然而,如前面的答案所示,这可能不是实现这一特定结果的最佳方式。

相关问题