首页 > 解决方案 > 删除熊猫数据框索引中的字符范围

问题描述

我在数据框列中有一个文本项列表,其中一些在末尾包含整数,而一些在括号“(额外信息)”之间包含信息。其余项目只是平面文本。我想从那些拥有它们的整数中删除所有整数,以及所有带有它们的信息的括号,同时仍然保留它所在的值。

             Cost   Item Purchased  Name
Store1       22.5   Sponge          Chris
Shop         2.5    Kitty Litter    Kevyn
House (aax)  2  Spoon               Filip

我希望输出是

           Cost Item Purchased  Name
Store      22.5 Sponge          Chris
Shop       2.5  Kitty Litter    Kevyn
House      2    Spoon           Filip

标签: pythondataframe

解决方案


设置数据框。如果您将其放在问题中,它将在将来很有用。

df = pd.DataFrame(
    {
        "cost": [22.5, 2.5, 2],
        "item purchased": ["Sponge", "kitty litter", "spoon"],
        "name": ["Chris", "Kevyn", "Filip"],
    },
    index=["Store1", "Shop", "House (aax)"],
)


# reset the index to a column.
df=df.reset_index()

# split the index and keep the first item in the lists.
df['index'] = df['index'].str.split("(").map(lambda x: x[0])

# reset the index
df = df.set_index('index')

print(df)

        cost    item purchased  name
index           
Store1  22.5    Sponge          Chris
Shop    2.5     kitty litter    Kevyn
House   2.0     spoon           Filip

推荐阅读