我有這個簡化的 DataFrame,我想在其中添加一個新列 Distance_km。在這個新列中,所有值都應該以公里為單位并轉換為 float dtype。
d = {'Point': ['a','b','c','d'], 'Distance': ['3km', '400m','1.1km','200m']}
dist=pd.DataFrame(data=d)
dist
Point Distance
0 a 3km
1 b 400m
2 c 1.1km
3 d 200m
Point object
Distance object
dtype: object
我怎樣才能得到這個輸出?
Point Distance Distance_km
0 a 3.8km 3.8
1 b 400m 0.4
2 c 1.1km 1.1
3 d 200m 0.2
Point object
Distance object
Distance_km float64
dtype: object
提前致謝!
uj5u.com熱心網友回復:
您也可以嘗試以下操作:檢查字串的倒數第二個字符是否為“k”。
- 如果是則只洗掉最后兩個字符,即'km'
- 否則取除最后一個字符(即“m”)之外的字符并將浮點值除以 1000
下面是使用applytoDistance列的實作:
dist['Distance_km'] = dist['Distance'].apply(lambda row: float(row[:-1])/1000 if not row[-2]=='k' else row[:-2])
結果是:
Point Distance Distance_km
a 3km 3
b 400m 0.4
c 1.1km 1.1
d 200m 0.2
uj5u.com熱心網友回復:
您可以使用 Pandas應用方法將距離列值傳遞給將其轉換為標準化單位的函式,如下所示
從檔案
沿 DataFrame 的軸應用函式。
傳遞給函式的物件是 Series 物件,其索引是 DataFrame 的索引 (axis=0) 或 DataFrame 的列 (axis=1)。默認情況下(result_type=None),最終回傳型別是從應用函式的回傳型別推斷出來的。否則,它取決于 result_type 引數。
首先創建將轉換資料的函式,apply甚至可以接受 lambda
import re
def convert_to_km(distance):
'''
distance can be a string with km or m as units
e.g. 300km, 1.1km, 200m, 4.5m
'''
# split the string into value and unit ['300', 'km']
split_dist = re.match('([\d\.] )?([a-zA-Z] )', distance)
value = split_dist.group(1) # 300
unit = split_dist.group(2) # km
if unit == 'km':
return float(value)
if unit == 'm':
return round(float(value)/1000, 2)
d = {'Point': ['a','b','c','d'], 'Distance': ['3km', '400m','1.1km','200m']}
dist=pd.DataFrame(data=d)
然后,您可以將此功能應用于您的距離列
dist['Distanc_km'] = dist.apply(lambda row: convert_to_km(row['Distance']), axis=1)
dist
輸出將是
Point Distance Distanc_km
0 a 3km 3.0
1 b 400m 0.4
2 c 1.1km 1.1
3 d 200m 0.2
uj5u.com熱心網友回復:
嘗試:
# An "Weight" column marking those are in "m" units
dist["Weight"] = 1e-3
dist.loc[dist["Distance"].str.contains("km"),"Weight"] = 1
# Extract the numeric part of string and convert it to float
dist["NumericPart"] = dist["Distance"].str.extract("([0-9.] )\w ").astype(float)
# Merge the numeric parts with their units(weights) by multiplication
dist["Distance_km"] = dist["NumericPart"] * dist["Weight"]
你會得到:
Point Distance Weight NumericPart Distance_km
0 a 3km 1.000 3.0 3.0
1 b 400m 0.001 400.0 0.4
2 c 1.1km 1.000 1.1 1.1
3 d 200m 0.001 200.0 0.2
順便說一句:apply如果可以,請避免使用,如果您的資料很大,那將非常慢。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468413.html
下一篇:Pandas隨機資料選擇
