转换熊猫数据框中列中的行元素

时间:2021-06-17 13:07:15

标签: pandas dataframe

问题:

                               df['bua']          
                      
                      0        Built-up Area 97 Sq Yards
                      1        Built-up Area 85 Sq Yards
                      2        Built-up Area 80 Sq Yards
                      3       Built-up Area 100 Sq Yards
                      4        Built-up Area 87 Sq Yards
                                          ...            
                      1832     Built-up Area 73 Sq Yards
                      1833     Built-up Area 80 Sq Yards
                      1834     Built-up Area 82 Sq Yards
                      1835    Built-up Area 1500 Sq Feet
                      1836     Built-up Area 66 Sq Yards
                      Name: bua, Length: 1837, dtype: object

我需要将 'bua' 列的上述每个元素转换为平方英尺。 还要删除末尾的“建筑面积”、“脚”、“码”。

输出:

输出应该是这样的

                                   df['bua']
                        
                          0        XX97         ^
                          1        XX85         |
                          2        XX80         | 
                          3        XX10         | # Values in sq-feet after conversion
                          4        XX87         | 
                                   ...          |   
                          1832     XX73         |
                          1833     XX80         | # Values in sq-feet after conversion
                          1834     XX82         |
                          1835     XX15         |
                          1836     XX66         V
                          Name: bua, Length: 1837, dtype: object

2 个答案:

答案 0 :(得分:0)

去除“建成区”,使用pandas系列的string方法:

df['bua'] = df['bua'].str.replace('Built-up Area', '')

接下来,您应该将码转换为英尺,但仅限于将码作为后缀的位置。再次使用 pandas str 方法在 'sq '处拆分字符串:

idx = df['bua'].str.split('sq ').str[-1] == 'Yards'
df.loc[idx, 'SquareFeet'] = df.loc[idx, 'bua'].str.split('sq ').str[0].astype(float) * 3
# Where the metric is in feet, just take the number
df.loc[~idx, 'SquareFeet'] = df.loc[~idx, 'bua'].str.split('sq ').str[0].astype(float)

然后您有一个名为“SquareFeet”的列,其中包含请求的数据

答案 1 :(得分:0)

使用 df['bua']=df['bua'].replace(regex=True,to_replace="[^0-9]",value=' ') 删除“建筑面积”、“英尺”、“码”。

使用df['bua'] = df['bua'].astype (float)将字符串转换为浮点数,然后应用以下代码

使用 df['Sq.Feet'] = df['bua'].apply(lambda x : x * 3) 将码转换为平方英尺,因为 1 码 = 3 英尺。

.apply() 将特定函数应用于数据框特定列中的每个元素。由于我没有完整的数据集,我无法尝试这些代码。