简体   繁体   English

如何使用for循环过滤Pandas数据框列中的字符串

[英]How to filter a string in a column of Pandas data frame using for loop

How can I use 'for' loop (eg ' for i in range(1996,2000,1) ') in string filtering of Pandas data frame ?如何在 Pandas 数据框的字符串过滤中使用“for”循环(例如“ for i in range(1996,2000,1) ”)?

I have a data frame like this:我有一个这样的数据框:

Date            Value
07/09/1997      505
05/03/1998      1005
03/02/2000      747
01/05/1998      448
06/08/1996      57
09/11/2000      673

I like to filter '1998' from the 'Date' column using a ' for i in range(1996,2000,1) ' loop and create a new DF so that it would look like this:我喜欢使用 ' for i in range(1996,2000,1) ' 循环从 'Date' 列中过滤 '1998' 并创建一个新的 DF,使其看起来像这样:

Date            Value
05/03/1998      1005
01/05/1998      448

for loops are slower, should be ideally avoided if possible . for循环较慢,最好尽可能避免

Convert Date column to datetime using pd.to_datetime and then extract only year using Series.dt.year :使用pd.to_datetimeDate列转换为datetime pd.to_datetime ,然后使用Series.dt.year仅提取year

In [2441]: df.Date = pd.to_datetime(df.Date)
In [2446]: df = df[df.Date.dt.year.eq(1998)]

In [2447]: df
Out[2447]: 
        Date  Value
1 1998-05-03   1005
3 1998-01-05    448

Additionally, per @CainãMaxCouto-Silva's comment:此外,根据@CainãMaxCouto-Silva 的评论:

You can filter a range of years as well:您还可以过滤一系列年份:

In [2451]: df[df.Date.dt.year.isin(range(1996,2000))]
Out[2451]: 
        Date  Value
0 1997-07-09    505
1 1998-05-03   1005
3 1998-01-05    448
4 1996-06-08     57

Another way其它的办法

df.Date = pd.to_datetime(df.Date)
df[df.Date.dt.isocalendar().year.eq(1998)]



        Date  Value
1 1998-05-03   1005
3 1998-01-05    448

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

相关问题 如何使用动态字符串通过Python Pandas过滤数据框 - How to use dynamic string to filter data frame using Python Pandas 使用循环过滤熊猫数据框中的多列 - Filter on multiple columns in pandas data frame using a loop 根据列名过滤数据框,而不使用pandas中的索引 - Filter the data frame based on the column names without using index in pandas python / pandas-如何通过列的组件过滤数据框 - python / pandas - how to filter a data frame by a component of a column 如何在另一个列值中具有条件的子组中筛选熊猫数据帧 - How to filter pandas data frame by subgroups with a condition in another column value 如何过滤熊猫数据框? - How to filter pandas data frame? 如何在不使用列名的情况下使用熊猫过滤行-循环过滤器 - How to filter rows with pandas without using the column name - loop filter 在pyspark中,如何通过一列数据框循环过滤功能? - In pyspark, how to loop filter function through a column of data frame? 如何在具有列值的 pandas 数据帧中使用 if else 与 for 循环 - how to used if else with for loop in pandas data Frame with Column value 如何根据来自不同数据帧的列中的条目在数据帧上应用 Pandas 过滤器(无连接) - How to apply a Pandas filter on a data frame based on entries in a column from a different data frame (no join)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM