如何使用 Python 从 CSV 数据集中消除空值单元格?

每行代表一个人(共 315 个),每列代表一个选择场景(共 16 个)。每个人随机响应 4 个连续的选择场景。我希望有四列连续包含每个人的回答并去掉任何空白单元格。Image of the excel sheet


import pandas as pd

df = pd.read_csv(r"C:\Users\Admin\Desktop\Book2.csv")

for (r,c) in df.iterrows():

if df.iat[r,c] is not None:

    for i in range(4):

        print(str(df.iat[r,c+i]))

更新 我已经设法将数据逐行放入一个列表中,并将它们分组为 4 组(因为我需要它)。现在如何保持元素的值不是 ' '?


import csv

rowdata = []

with open(r'C:\Users\ARPLAB31\Desktop\SPdata.csv') as inputfile:

    reader = csv.reader(inputfile)

    rowdata = list(reader)

r= []

for i in range(1,718,1):

    for j in range(28):

        if len(rowdata[i][j])!=0:

            r.append(rowdata[i][j])

cardref = [r[x:x+4] for x in range(0, len(r),4)] '''cardref contains the partitioned data.'''

print(cardref)

输出:


[[' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], ['BB', 'BB', 'CC', 'CC '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], ['CC', 'BB', 'CC', 'CC'], [' ', ' ', ' ' , ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ',' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], ['CC', 'CC', 'CC', 'CC'], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], ['CC', 'CC' , 'AA', 'CC'], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ' ], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ' , ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ',' ', ' '], [' ', ' ', ' ', ' '], ['CC', 'BB', 'CC', 'CC'], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ']]


MMTTMM
浏览 502回答 3
3回答

慕莱坞森

您可以读取每一行,获取非空字段,然后从那里创建一个新的 CSV。例如:data = ",,2,2,2,2,,,"arr = filter(None, data.split(",")) #removes null fields",".join(arr) #"2,2,2,2"

蝴蝶不菲

使用 df.isnull() [其中 df 是熊猫数据框]在熊猫的数据框中查找空值的好资源。https://dzone.com/articles/pandas-find-rows-where-columnfield-is-null
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python