python - 数据框中的循环函数

标签 python pandas

我将数据存储在 DataFrame 中,并且我有函数来操作每一行并将其存储为新的 DataFrame 格式。

import pandas as pd  

def get_data(start_time):  
    from datetime import datetime, timedelta
    start_time = datetime.strptime(start_time)
    ten_second = start_time + timedelta(0,10)
    twenty_second = start_time + timedelta(0,20)
    combine = {'start' : ten_second, 'end' : twenty_second}
    rsam=pd.DataFrame(combine, index=[0])
    return(rsam)


df_event = pd.DataFrame([["2019-01-10 13:16:25"],
             ["2019-01-29 13:56:21"],
             ["2019-02-09 14:41:21"],
             ["2019-02-07 11:28:50"]])

temp=[]
for index, row in df_event.iterrows():
    temp=get_data(row[0])

我在互联网上看到他们建议我使用 iterrows() 但我的循环函数仍然出错

我对 temp 变量的期望

Index          ten_second            twenty_second
  0         2019-01-10 13:16:35   2019-01-10 13:16:45
  1         2019-01-29 13:56:31   2019-01-29 13:56:41
  3         2019-02-09 14:41:31   2019-02-09 14:41:41
  4         2019-02-17 11:29:00   2019-02-17 11:29:10

最佳答案

您不需要 iterrows 或您的函数。只需使用pd.Timedelta:

c1 = df_event[0] + pd.Timedelta('10s')
c2 = df_event[0] + pd.Timedelta('20s')

temp = pd.DataFrame({'ten_second':c1,
                     'twenty_second':c2})

输出

           ten_second       twenty_second
0 2019-01-10 13:16:35 2019-01-10 13:16:45
1 2019-01-29 13:56:31 2019-01-29 13:56:41
2 2019-02-09 14:41:31 2019-02-09 14:41:41
3 2019-02-07 11:29:00 2019-02-07 11:29:10
<小时/>

如果您需要更多这些列,或者编写一个函数:

def add_time(dataframe, col, seconds):

    newcol = dataframe[col] + pd.Timedelta(seconds)

    return newcol

temp = pd.DataFrame({'ten_second':add_time(df_event, 0, '10s'),
                    'twenty_second':add_time(df_event, 0, '20s')})

输出

           ten_second       twenty_second
0 2019-01-10 13:16:35 2019-01-10 13:16:45
1 2019-01-29 13:56:31 2019-01-29 13:56:41
2 2019-02-09 14:41:31 2019-02-09 14:41:41
3 2019-02-07 11:29:00 2019-02-07 11:29:10
<小时/>

或者我们可以使用分配在一行中完成此操作:

temp = pd.DataFrame().assign(ten_second=df_event[0] + pd.Timedelta('10s'), 
                             twenty_second=df_event[0] + pd.Timedelta('10s'))

关于python - 数据框中的循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57398115/

相关文章:

python - 是否有任何基准显示 `collections.deque` 的良好性能?

python - 如何删除 Pandas 中包含特定字符串的任何行?

python - 绘制按列分组的 Pandas 数据框

python - 如何在 Python 中重写 DataFrame 中的列的字段?

没有真实性验证的python ssh

python从多索引数据帧绘图

python - 从 Pandas 中的相关矩阵返回最高和最低相关

python - 使用 Python 中的聚类进行 ScatterPlot 着色和标记

javascript - 如何有效地从 Pandas 数据框转移到 JSON

python - 导入错误 : cannot import name 'DtypeArg' from 'pandas