【发布时间】:2020-06-03 08:21:08
【问题描述】:
我试图只提取两个不同数据帧中的数字和字符串。我正在使用正则表达式来提取数字和字符串。
import pandas as pd
df_num = pd.DataFrame({
'Colors': ['lila1.5', 'rosa2.5', 'gelb3.5', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
'esel20']
})
for column in df_num.columns:
df_num[column] = df_num[column].str.extract('(\d+)').astype(float)
print(df_num)
我也尝试过使用'([\d+][\d+\.\d+])' and '([\d+\.\d+])'
在这里我得到了输出,但不是我所期望的。虽然我期待浮点数,但我没有得到 1.5 或 2.5。
我得到类似下图的东西:
df_str = pd.DataFrame({
'Colors': ['lila1.5', 'rosa2.5', 'gelb3', 'grün4', 'rot5', 'schwarz6', 'grau7', 'weiß8', 'braun9', 'hellblau10'],
'Animals': ['hu11nd', '12welpe', '13katze', 's14chlange', 'vo15gel', '16papagei', 'ku17h', '18ziege', '19pferd',
'esel20']
})
for column in df_str.columns:
df_str[column] = df_str[column].str.extract('([a-zA-Z]+)')
print(df_str)
在这种情况下,当数字在末尾或开头时,我会得到字符串,但如果数字放在中间或任何其他地方,那么我期望我不会得到结果。 当前输出如下图:
我认为我的正则表达式不正确。哪个是解决这些问题的正确正则表达式?或者有没有其他方法可以只提取熊猫数据框中的数字和字符串?
【问题讨论】:
标签: python-3.x pandas dataframe data-science text-extraction