首页 > 解决方案 > 如何从数据框中的字符串中提取数字并将这些数字的倍数添加到同一数据框的新列中

问题描述

这是我如何设法从维度中提取数值并将它们相乘以返回体积的示例:

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)

有人可以帮助我将这些卷数据作为新列恢复到原始数据框中。

标签: pythonpandasnumpydataframe

解决方案


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

推荐阅读