删除pandas dataframe index中的字符范围

问题描述 投票:0回答:1

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

             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
python dataframe
1个回答
0
投票

Set up the dataframe. It would be useful in future if you put this in the question.

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
© www.soinside.com 2019 - 2024. All rights reserved.