我对熊猫知识渊博
所以我遇到了以下问题:
我想根据字符串列
获取天数Period
3 days
5 weeks
1 year
我想将此列转换为整数,这是这样的天数:
Days
3
35
365
我做了如下:
def toDays(dt):
if 'year' in dt:
for s in dt:
if s.isdigit():
return int(s)*360
elif 'month' in dt:
for s in dt:
if s.isdigit():
return int(s)*30
elif 'week' in dt:
for s in dt:
if s.isdigit():
return int(s)*7
if 'day' in dt:
for s in dt:
if s.isdigit():
return int(s)
train_file["Days"]=train_file["Periods"].map(toDays)
但是没有用,我会帮助将此功能映射到数据框
答案 0 :(得分:3)
代码 -
import pandas as pd
def convert(s):
ls = s.split()
d = {'day': 1, 'week': 7, 'month': 30, 'year': 360}
for k, v in d.items():
if ls[1].startswith(k):
return int(ls[0]) * v
df = pd.DataFrame({'Col': ['3 days', '5 weeks', '1 year']})
df['Col'] = df['Col'].apply(convert)
print(df)
输出 -
Col
0 3
1 35
2 360