繁体   English   中英

在 Pandas 中达到某个值时的列长度

[英]Length of column when in reaches a certain value in Pandas

当时间列达到 5 分钟(秒不重要)时,我想取列的长度。 例如,当时间达到 5 时,此文件中的列长度为 436。 时间列的类型为 object。 有多个文件,我无法为每个文件手动执行此操作。 这是我在项目中导入的 txt 文件的示例。

Time    Sample #  
0:00.050       18     
0:00.308      111    
0:00.953      343    
0:01.586      571    
0:02.242      807     
0:02.911     1048     
0:03.575     1287     
0:04.231     1523     
0:04.903     1765     
0:05.539     1994     
0:06.164     2219    
0:06.764     2435    
0:07.392     2661    

假设您已经有一个 Dataframe 由您显示的表格组成,有两列(“时间”和“样本”):

import pandas as pd
from datetime import datetime

# function to convert string into datetime, if 'Time' is not in datetime format yet
str_dt = lambda x: datetime.strptime(x, '%M:%S.%f')
df.Time = df.Time.apply(lambda x: str_dt(x))
# set column 'Time' as index
df = df.set_index('Time')

# get the minute for each index entry
idx_minute = lambda x: x.minute

# find the position of all entries when reading 5 minutes
length_5_minute = np.where(df.apply(lambda x: idx_minute(x.index)) == 5)[0]

# The position of the first entry when reahing 5 minutes
length_5_minute = length_5_minute[0]\
                    if len(length_5_minute) > 0\
                    else []

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM