python - 删除熊猫数据框索引中的字符范围
问题描述
我在数据框列中有一个文本项列表,其中一些在末尾包含整数,而一些在括号“(额外信息)”之间包含信息。其余项目只是平面文本。我想从那些拥有它们的整数中删除所有整数,以及所有带有它们的信息的括号,同时仍然保留它所在的值。
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
解决方案
设置数据框。如果您将其放在问题中,它将在将来很有用。
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
推荐阅读
- javascript - 如果没有文件怎么做它什么也不做
- sql - 如何排除闪回查询结果集中未更改的字段?
- angular - 如何在 Angular 中对对象进行深度复制?
- mysql - 错误代码:1214。使用的表类型不支持 FULLTEXT 索引 - 在 Mysql 8.0 中使用 UNION 时
- r - data.frame 使用名称向量
- discord.py - 如何小写响应 discord.py
- c# - 发现重复的类 facebook sdk unity
- python - 如何删除列表索引位置?
- django - 如何在 Django 中的用户注册表单中检索 Employee 模型的数据
- python - Python代码没有得到正确的输出?