当单元格为空时删除行

2024-07-01 08:38:32 发布

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

当“carries.xlsx”电子表格中的单元格为空时,我试图删除一行,并将所有数据(空行除外)发送到“destination.xlsx”电子表格。下面的代码是我走了多远。但是,它仍然不会删除基于卡路里列的空值行

这是数据集:

Data Set

如何开发代码来解决此问题

import pandas as pd

FileName = 'calories.xlsx'
SheetName = pd.read_excel(FileName, sheet_name = 'Sheet1')

df = SheetName

print(df)

ListCalories = ['Calories']

print(ListCalories)

for Cell in ListCalories:
    if Cell == 'NaN':
        df.drop[Cell]

print(df)

df.to_excel('destination.xlsx')

Tags: 数据代码dfcellfilenamexlsxexceldestination
2条回答

创建虚拟数据

df=pd.DataFrame({
    'calories':[2306,3256,1235,np.nan,3654,3256],
    'Person':['person1','person2','person3','person4','person5','person6',]
    })

打印数据框

    calories    Person
0   2306.0  person1
1   3256.0  person2
2   1235.0  person3
3           person4
4   3654.0  person5
5   3256.0  person6

如果缺少卡路里值,则删除行

new_df=df.dropna(how='any',subset=['calories'])

结果

    calories    Person
0   2306.0     person1
1   3256.0     person2
2   1235.0     person3
4   3654.0     person5
5   3256.0     person6

另存为excel

new_df.to_excel('destination.xlsx',index=False)

您的ListCalories只包含一个元素Calories,我假设这是一个输入错误。 你可能想做的是

import pandas as pd

FileName = 'calories.xlsx'
df = pd.read_excel(FileName, sheet_name = 'Sheet1')

print(df)

# you don't need this, but I kept it for you
ListCalories = df['Calories']
print(ListCalories)

clean_df = df[df['Calories'].notna()] # this will only select the rows that doesn't have na value in the Calories column

print(clean_df)

clean_df.to_excel('destination.xlsx')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.notna.html

相关问题 更多 >

    热门问题