繁体   English   中英

使用python从excel表中删除值

[英]Remove values from excel sheet using python

我有一个 excel 工作簿,它由一个有 4 列的工作表组成,即。 (旅客编号,from,to,medium)并包含旅客到达目的地的路线。 可以根据旅客为到达目的地所做的更改次数重复旅客编号。

我的问题是,如何只保留相关数据,同时使用 python 删除所有其他具有“无信息”的单元格值。

示例工作表:

旅行者号 中等的
1个 曼彻斯特 伦敦 火车
2个 德比 考文垂 火车
2个 德比 考文垂 火车
3个 利物浦 曼彻斯特 无信息
3个 曼彻斯特 伦敦 航班
3个 伦敦 温布利 公共汽车
4个 4. 没有信息 伍尔弗汉普顿 4. 没有信息
5个 5. 没有信息 5. 没有信息 5. 没有信息
6个 6. 暂无信息 6. 暂无信息 6. 暂无信息
7 7. 暂无信息 7. 暂无资料 7. 暂无资料
8个 8. 没有信息 8. 没有信息 8. 没有信息

我假设您正在使用 pandas 库。 在这种情况下,您可以遍历列标题,具有字符串“No information”的列将用于删除整行。

df = df[df["from|to|medium"].str.contains("No information") == False]

如果代码不起作用,请尝试使用以下部分(即只添加“来自”)。

"from|to|medium"

ps 名为 df 的变量是您需要选择的数据框。

首先,您需要使用 pandas 加载数据框。

import pandas as pd
df = pd.read_excel('path/to/file.xlsx')
df
    traveller no.            from              to          medium
0               1      manchester          london           train
1               2           derby        coventry           train
2               2           derby        coventry           train
3               3       liverpool      manchester  No information
4               3      manchester          london          flight
5               3          london         wembley             bus
6               4  No information   wolverhampton  No information
7               5  No information  No information  No information
8               6  No information  No information  No information
9               7  No information  No information  No information
10              8  No information  No information  No information

之后,您需要指定要检查的确切列,并将“No information”替换为更常见的 NaN:

df = df[df != 'No information']
df
    traveller no.        from             to  medium
0               1  manchester         london   train
1               2       derby       coventry   train
2               2       derby       coventry   train
3               3   liverpool     manchester     NaN
4               3  manchester         london  flight
5               3      london        wembley     bus
6               4         NaN  wolverhampton     NaN
7               5         NaN            NaN     NaN
8               6         NaN            NaN     NaN
9               7         NaN            NaN     NaN
10              8         NaN            NaN     NaN

它将用 NaN 替换所有“无信息”实例。 现在您可以使用更广泛的方法通过dropna()函数删除 NaN 值:

df = df.dropna(subset=['from', 'to', 'medium'])
df
      traveller no.        from        to  medium
0              1  manchester    london   train
1              2       derby  coventry   train
2              2       derby  coventry   train
4              3  manchester    london  flight
5              3      london   wembley     bus

关键字subset将删除指定列中至少有一个缺失值的所有行。 如果您想要一些不同的行为,请访问文档: https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html

暂无
暂无

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

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