Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用函数映射字符串列_Python_Pandas - Fatal编程技术网

Python 使用函数映射字符串列

Python 使用函数映射字符串列,python,pandas,Python,Pandas,我对熊猫不是很了解 所以我有一个问题如下: 我想获得基于字符串列的天数 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

我对熊猫不是很了解

所以我有一个问题如下:

我想获得基于字符串列的天数

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)
但是这不起作用,为了将这个函数映射到数据帧代码中,我需要一些帮助-

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

这不是一种映射序列而不是创建数据帧的方法吗?