pandas 如何删除数据框架的最后六列没有NaN值,其中每行具有不同数量的值

qv7cva1a  于 2023-08-01  发布在  其他
关注(0)|答案(2)|浏览(110)

我有一个Pandas数据框架,它有两千多行和近一千列。问题是每行都有不同数量的列,这些列实际上有值。如果行中的值使用的列少于最长行,则其余值为NaN。
它看起来像这样:

0   1    2    3    4    5    6    7
A  Hip  22  Hop  Hat    3  NaN  NaN  NaN
B  Gig  45  Get  Gik    4  Goo    5  NaN
C  Lip  34  Lop    2  NaN  NaN  NaN  NaN
D  Fip  56  Fup  Fik  Fap  Fat  Fot  6.0

字符串
我正在尝试删除(并将其存储为单独的数据框架)每行不包含NaN值的最后两列。所以我想要的是这样的:

0   1    2    3    4    5    6   7
A  Hip  22  Hop  NaN  NaN  NaN  NaN NaN
B  Gig  45  Get  Gik    4  NaN  NaN NaN
C  Lip  34  NaN  NaN  NaN  NaN  NaN NaN
D  Fip  56  Fup  Fik  Fap  Fat  NaN NaN


我试图将数据框架转换为嵌套列表,在其中我可以简单地删除NaN值并删除每个列表的最后一列,但它崩溃了。
有什么想法吗

syqv5f0l

syqv5f0l1#

我会尝试这样的东西:

# create an empty list
lst = []

# cycle through the columns and see if they contain any nulls
# if not, append to list
for col in df.columns:
    if not df[col].isnull().values.any():
        lst.append(col)

# if there are at least six columns in your list
# do what you want with the last two (-1 is last, -2 is 2nd from last, ...)
# this shows putting them in a new df and dropping from the original
if len(lst) >= 6:
    new_df = df.filter([lst[-1], lst[-2], lst[-3], lst[-4], lst[-5], lst[-6]], axis = 1)
    df.drop(labels = [lst[-1], lst[-2], lst[-3], lst[-4], lst[-5], lst[-6]], axis = 1, inplace = True)

字符串

06odsfpq

06odsfpq2#

在反向列上使用notnacumsum计算掩码:

N = 2 # number of trailing non-NA values
m = df.iloc[:, ::-1].notna().cumsum(axis=1).gt(N)

out1 = df[m]
out2 = df[~m]

字符串
输出量:

# out1
     0   1    2    3    4    5    6   7
A  Hip  22  Hop  NaN  NaN  NaN  NaN NaN
B  Gig  45  Get  Gik    4  NaN  NaN NaN
C  Lip  34  NaN  NaN  NaN  NaN  NaN NaN
D  Fip  56  Fup  Fik  Fap  Fat  NaN NaN

# out2
     0   1    2    3    4    5    6    7
A  NaN NaN  NaN  Hat    3  NaN  NaN  NaN
B  NaN NaN  NaN  NaN  NaN  Goo    5  NaN
C  NaN NaN  Lop    2  NaN  NaN  NaN  NaN
D  NaN NaN  NaN  NaN  NaN  NaN  Fot  6.0


中间掩模m

7     6      5      4      3      2      1      0
A  True  True   True   True   True  False  False  False
B  True  True   True  False  False  False  False  False
C  True  True   True   True  False  False  False  False
D  True  True  False  False  False  False  False  False

相关问题