gpt4 book ai didi

python - 当单元格为空时删除一行

转载 作者:行者123 更新时间:2023-12-04 09:30:13 24 4
gpt4 key购买 nike

当“calories.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')

最佳答案

创建虚拟数据

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)

关于python - 当单元格为空时删除一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62877118/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com