python - 如何从数据框中的字符串中提取数字并将这些数字的倍数添加到同一数据框的新列中
问题描述
这是我如何设法从维度中提取数值并将它们相乘以返回体积的示例:
import pandas as pd
# create a dict
d = {'model': ['merc','ford'], 'dimensions': ['4.31 m x 2 m x 3.222 m', '2 m']}
# create data frame from dict
df = pd.DataFrame(data=d)
# this extracts all instances of numbers but creates a new data frame with each num in new row
x = df['dimensions'].str.extractall(r'(\d*\.?\d+)')
# converts all numeric strings to float
x[0] = x[0].astype(float)
#multiplies the dimensions of the van
y = x.loc[0].prod(axis=0)
print(y)
这是我尝试的函数,用于重复上面代码中的示例,但将其返回到数据框中的新列。
def my_function(col,row):
out = 0
if col.str.extractall(r'(\d*\.?\d+)') == True:
out = col.str.extractall(r'(\d*\.?\d+)')
col[0] = col[0].astype(float)
z = col.loc[row].prod(axis=0)
return z
# logic to create new column based on function and existing data.
df['volume'] = df.apply(lambda x: my_function(df['dimensions'], df.index)
有人可以帮助我将这些卷数据作为新列恢复到原始数据框中。
解决方案
IIUC,你想试试吗:
df['volume'] = df['dimensions'].str.extractall(r'(\d*\.?\d+)').astype(float).unstack().prod(axis=1)
输出:
model dimensions volume
0 merc 4.31 m x 2 m x 3.222 m 27.77364
1 ford 2 m 2.00000
推荐阅读
- reactjs - 嵌套应用程序的 IIS URL 重写
- javascript - 在 Chrome 和 Firefox 中调整图像大小时 contenteditable="true" 属性不适用于图像标签的解决方案
- python - PyPDF2.utils.PdfReadError:文件尚未解密
- java - 使用 SceneBuilder 在 JavaFX 项目开始时调用函数
- c++ - 谁能解释这个图像分辨率设置代码?到底发生了什么
- java - 在阻止模式下拨打电话
- c++ - 如何使用 Fast-LZMA2 压缩/解压缩缓冲区
- python - Anaconda导入错误,循环导入错误
- flutter - 没有为“DocumentReference”类型定义获取器“documentID”
- android - BasicNetwork.performRequest:带有 Volley 库的 newsapi.org 的意外响应代码 403