【问题标题】:python data frame - removing unwanted unicode rowspython dataframe - 删除不需要的unicode行
【发布时间】:2017-09-21 17:06:08
【问题描述】:

我在数据框中有一列“名称”。 我想删除所有行,它的名称不在 names_all 中:

names_all = ['alice', 'bob', 'david']

names_all 中的所有字符串和数据框都是 unicode 字符串。

我写了代码:

for index, row in history.iterrows():
    if row['name'] not in names_all:
        history.drop(index, inplace=True)

但由于某种原因,它正在做一些奇怪的事情。它删除了太多行(删除了所有 1700 首行等等)。 在我将所有字符串编码为 un​​icode 之前,它也做了一些奇怪的事情,但没有那么多。

【问题讨论】:

    标签: python pandas unicode


    【解决方案1】:

    你为什么不直接选择那些匹配names_all的:

    history = history.loc[history.name.isin(names_all)]
    

    【讨论】:

    • 在我看来他想删除不在列表中的行,他的代码使用not in
    【解决方案2】:

    解决方案 1:

    history = history[history['name'].isin(names_all)]
    

    解决方案 2:

    history = history.query("name in @names_all"]
    

    【讨论】:

    • 我不知道这种方法,但它不起作用。它弄乱了整个数据框。
    • @sheldonzy,对不起,我误解了你的问题。请立即检查...
    猜你喜欢
    • 2020-08-20
    • 2021-04-21
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2022-08-09
    • 2019-02-21
    • 2020-09-03
    相关资源
    最近更新 更多