从熊猫条件中获取行号和列号



我想根据给定条件获取行号和列号。"坐标",如果你愿意的话。

import re
import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [1,21,8,44,np.NaN,6,75,8,44,999], 
                    'B' : [1,1,3,5,0,0,np.NaN,9,0,0], 
                    'C' : ['AA1233445','AA1233445', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'], 
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Assign','Hello','Ugly','Appreciate','Undo','Testing','Unicycle','Pharma','Unicorn',]})
print(dfp)
       A    B           C            D           E
0    1.0  1.0   AA1233445     123456.0      Assign
1   21.0  1.0   AA1233445     123456.0      Assign
2    8.0  3.0       rmacy    1234567.0       Hello
3   44.0  5.0    Idaho Rx   12345678.0        Ugly
4    NaN  0.0    Ab123455      12345.0  Appreciate
5    6.0  0.0    TV192837      12345.0        Undo
6   75.0  NaN          RX   12345678.0     Testing
7    8.0  9.0  Ohio Drugs  123456789.0    Unicycle
8   44.0  0.0     RX12345    1234567.0      Pharma
9  999.0  0.0  USA Pharma          NaN     Unicorn

我可以通过执行以下操作来获得输出:

print(dfp.loc[dfp['B'].isnull()].index.values[0] + 1 ,
',', + int([i for i,x in enumerate(dfp.columns.tolist()) if x == 'B'][0] + 1))

但问题是B是否有多个空值。我想要所有零值的坐标。

有没有办法使用 dataframe.loc 或类似的东西来做到这一点?在值中添加 1 没什么大不了的,我以后可以轻松做到这一点。

您可以使用

dfp[pd.isnull(dfp['B'])].index.tolist()

要简洁地添加1,您可以使用:

np.asarray(dfp[pd.isnull(dfp['B'])].index) + 1

打印

print(np.asarray(dfp[pd.isnull(dfp['B'])].index) + 1)

要包括列 B 的索引 ( dfp.columns.get_loc("B") + 1 (:

for x in np.asarray(dfp[pd.isnull(dfp['B'])].index) + 1:
    print(str(x)+','+str(dfp.columns.get_loc("B") + 1))

要在给定的列列表中查找"NaN",请执行以下操作:

def find_NaN(list_col):
    for c in list_col:
        if c in dfp.columns:
            for x in np.asarray(dfp[pd.isnull(dfp[c])].index) + 1:
                print(str(x)+','+str(dfp.columns.get_loc(c) + 1))
find_NaN(["A","B"])
5,1
7,2

一些解释

dfp[pd.isnull(dfp['B'])]使用布尔值数组从数据帧中选择数据。

dfp.columns.get_loc(c)给出了列c的索引

def find_NaN(list_col):
    for c in list_col:
        # if column is one of the dataframe's columns
        if c in dfp.columns:
            # for each index x where column c of the dataframe is null
            for x in np.asarray(dfp[pd.isnull(dfp[c])].index) + 1:
                print(str(x)+','+str(dfp.columns.get_loc(c) + 1))

我会使用np.wherezip的组合

i, j = np.where(dfp.isnull().values)
# Coordinates in the space of the actual index and column names
list(zip(dfp.index[i], dfp.columns[j]))
[(4, 'A'), (6, 'B'), (9, 'D')]

否则,坚持使用序号位置

list(zip(i, j))
[(4, 0), (6, 1), (9, 3)]

np.column_stack([i, j])
array([[4, 0],
       [6, 1],
       [9, 3]])

最新更新