简体   繁体   English

如何使用 python 删除从 pandas 数据框转换而来的列表中包含空元素的行?

[英]How to remove lines with empty elements within a lists converted from a pandas data frame using python?

So I try to convert a pandas data frame to my customized class function and here is the code for it:所以我尝试将 pandas 数据框转换为我自定义的 class function ,这是它的代码:

import os
import pandas as pd
import math
cwd = os.path.abspath('') 
files = os.listdir(cwd)  
df = pd.DataFrame()
for file in files:
    if file.endswith('.XLSX'):
        df = df.append(pd.read_excel(file), ignore_index=True)
#print(df)
array = df.values.tolist()
print(array)

class Item():
    
    def __init__(self, name, cost, gender, prime):
        self.__name = name
        self.__cost = cost
        self.__gender = gender
        self.__prime = prime

    def __repr__(self):
        return f"Item({self.__name},{self.__cost},{self.__gender},{self.__prime})"
    


mylist = [Item(*k) for k in array if k[0] and k[1] and k[2] and k[3]]
#print(mylist)

However, there are missing elements in the data frame, so when converting it to the list using array = df.values.tolist() instead of being an "None" for the empty part, the result would produce "nan" instead.但是,数据框中缺少元素,因此当使用array = df.values.tolist()将其转换为列表而不是空部分的“无”时,结果将生成“nan”。 This, in fact will cause the filtering process in "mylist" not working.这实际上会导致“mylist”中的过滤过程不起作用。

So, can you should me the code to do instead.所以,你能不能给我代码来代替。 Thank you in advance.先感谢您。

Much easier to do while it's still a pandas DataFrame. If you insert a当它仍然是 pandas DataFrame 时更容易做到。如果你插入

df.dropna(inplace=True)

before you df.values.tolist() then any rows with missing values should be removed.df.values.tolist()之前,应删除任何缺少值的行。

There are two ways有两种方式

  1. Use filter使用filter
import math
...
array = df.values.tolist()
array = filter(lambda e: all(map(lambda ee: not isinstance(ee, (float, int) or not math.isnan(ee), e)), array))
...

  1. Use pandas使用 pandas
...
df = df.dropna()
array = df.values.tolist()
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM