【发布时间】:2018-06-13 06:04:55
【问题描述】:
我在列 A中有以下文字:
A
hellothere_3.43
hellothere_3.9
我只想提取数字到另一个新列 B(A 旁边),例如:
B
3.43
3.9
我使用:str.extract('(\d.\d\d)', expand=True),但这复制只有 3.43(即确切的位数)。有没有办法让它更通用?
非常感谢!
【问题讨论】:
我在列 A中有以下文字:
A
hellothere_3.43
hellothere_3.9
我只想提取数字到另一个新列 B(A 旁边),例如:
B
3.43
3.9
我使用:str.extract('(\d.\d\d)', expand=True),但这复制只有 3.43(即确切的位数)。有没有办法让它更通用?
非常感谢!
【问题讨论】:
使用正则表达式。
例如:
import pandas as pd
df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
df["B"] = df["A"].str.extract("(\d*\.?\d+)", expand=True)
print(df)
输出:
A B
0 hellothere_3.43 3.43
1 hellothere_3.9 3.9
【讨论】:
我认为字符串拆分和应用 lambda 非常干净。
import pandas as pd
df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
df["B"] = df['A'].str.split('_').apply(lambda x: float(x[1]))
我没有进行任何适当的比较,但它似乎比小型测试的正则表达式解决方案更快。
【讨论】: