python - 将 pandas 列从 15 年 4 月 3 天的字符串转换为 15.3 年

标签 python pandas

我的一个专栏有一个问题,该专栏的数据如下所示,我希望将其计算为年数。

enter image description here

我尝试使用 df.apply 并将它们分开,但我被困在这里。公式应类似于 conversion_years = 年 + 月/12 + 天/365

import pandas as pd 

df = pd.read_csv('C:/csv')

def years(c):
     y = []

     m = []

     d = []

     text = (c['years of service'])

     g= text.split(' ')        

df['converted_years'] = df.apply(years,axis = 1)

结果应该是这样的

converted_years
---------------------
10.8

15.3

0.2

2.0

0.7

10.9

0.0

1.9

最佳答案

所以你要做的就是定义一个函数来分割字符串,应用公式并返回所需的数字。

您可以创建一个新列:

df['converted_years'] = df['years of service'].apply(parse_string)
def parse_string(duration_str):

    temp_list = duration_str.split(' ')

    strings = ['years(s)', 'months(s)', 'days(s)']

    duration = {}

    for i, string in enumerate(strings):
        if string in temp_list:
            idx = temp_list.index(string) - 1
            duration[i] = float(temp_list[idx])
        else:
            duration[i] = 0

    return duration[0] + duration[1] / 12 + duration[2] / 365

该函数在字符串 'years(s)''months(s)''days(s)' 的情况下工作> 完全一样。

这应该会给你答案。

关于python - 将 pandas 列从 15 年 4 月 3 天的字符串转换为 15.3 年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56171997/

相关文章:

python - 在 pandas 中重新采样,将日期时间系列拆分为 "n"分钟存储桶并为每个存储桶计数

python - 我们如何在 python 中转换 01-01-2011 19 :00 to weekdays like Mon , Tue ..?

python - 在 python 中,如何将十六进制 ascii 字符串转换为原始内部二进制字符串?

python - 是否有可用于额外参数的 pip 环境变量?

python - 由于python中的双反斜杠导致的sql语法错误

python - 如何使用动态日期范围计算唯一值

python - 如何在 Pandas 中组合宽数据框和长数据框?

Python Pandas 替换列名

Python:从一个文件夹中导入多个图像并将它们缩放/组合成一个图像?

Python/Pandas - 将 3 个数据集组合成一个柱形图