如何在python中基于两个不同CSV文件中的空值分离数据

2024-06-16 12:41:10 发布

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

我是python开发的新手,我正在尝试基于空值将csv文件分为两个不同的文本文件

我的csv文件有如下数据

enter image description here

以及

enter image description here

我的csv文件包含四个字段facility、Truck、Driver和license truck和driver有一些空值 我想为truck value为null的行值创建两个单独的文件,另一个文件将包含driver value为null的信息

我尝试了以下代码,但它并没有消除空值,它在文本文件中显示0或空格

    License = pd.read_csv("E:\ActiveCityLicenses.csv")

    a=License.isnull().sum()
    print(a)
    print(License.shape)
    m=License[License['TRUCK_ID'].isnull()]
    print(m)
    n=License.dropna(axis= 0, subset= ['TRUCK_ID'], inplace=True)
    print(n)

    License.to_csv(r'E:\DriverLicense.txt', header=None, index=None, mode='w', columns=None)
    #I had to create two data frames as after doing first dorpna entire frame gets empty


    License1 = pd.read_csv("E:\ActiveCityLicenses.csv")
    p=License1.dropna(axis= 0, subset= ['EMPLOYEE_ID'], inplace=True)
    print(p)

    License1.to_csv(r'E:\TruckLicense.txt', header=None, index=None, sep=',', mode='w')

有没有人能建议一个更好的方法,或者我在这里遗漏了什么? 文本文件中的输出为

     A119,BF01,,TOR|MARK|BRAM|MISS|RHILL|VAU
     A119,BF03,,TOR|MARK|BRAM|MISS|RHILL|VAU
     A119,BF04,,TOR|MARK|BRAM|MISS|RHILL|VAU
     A119,BF05,,TOR|MARK|BRAM|MISS|RHILL|VAU

空间不应该存在


Tags: 文件csvnoneidlicensetormark空值
2条回答
df= df[pd.notnull(df['TRUCK_ID'])]

如果要确保不存在空列,则始终可以通过执行以下操作来删除该列,例如: License.drop(labels="EMPLOYEE_ID", axis=1, inplace=True) 我不完全确定您要删除哪一列,所以我不能给出一个更完整的解决方案

相关问题 更多 >