簡體   English   中英

從 dataframe 字符串列中提取日/年並求和 [Python]

[英]Extract day/year from dataframe string column and sum it [Python]

我在 dataframe 中有一個名為“時間”的列,它具有字符串格式。 我想從該列的每個單元格的字符串中提取年份和日期數字,創建一個新列,其中年份數字乘以 365,如果根據以下計算添加可用的日期數字。 關於如何解決這個問題的任何建議?

提前謝謝了。

在此處輸入圖像描述

這不是最有效或最穩健的解決方案。 這是一個 function 可以從time列中獲取您的一個字符串並返回output

def foo(s):
    result = 0
    l = s.split()
    for i, word in enumerate(l):
        if not word.isdigit():
            continue
        # word is number
        if l[i+1] == 'year':  # unit is years
            result += int(word) * 365
        else:  # unit is days
            result += int(word)
    return result

print(foo('5 day'))  # 5
print(foo('2 year'))  # 730
print(foo('3 year 10 day'))  # 1105

或者,如果您更喜歡單線

def foo(s):
    return sum(int(word) * (365 if s.split()[i+1] == 'year' else 1) for i, word in enumerate(s.split()) if word.isdigit())

有很多方法可以做到這一點。

一種方法是這樣做。

另一種方法是將“時間”分成幾個這樣的列

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM