从熊猫日期框中提取行

时间:2021-04-02 11:33:18

标签: python-3.x pandas dataframe

我有一个如下图所示的数据框。我想提取年份和月份为“1395/01”的数据框行。我使用了下面的代码,但我知道它不正确,因为我们可以在一系列字符串上使用字符串切片。谁能告诉我一种不使用嵌套 for 循环的方法?

df[df['Date'][:7] == '1395/01']

enter image description here

2 个答案:

答案 0 :(得分:1)

我可能会在这里使用 str.match

df[df['Date'].str.match(r'^1395/01')]

但通常最好将日期存储为 datetime 而不是文本。此外,1395 年似乎很可疑。

答案 1 :(得分:1)

您可以使用 loc 和 startswith 来过滤您的数据框。

示例:

df = pd.DataFrame({'Date': ['1395/01/01', '1395/02/01', '1395/01/01', '1395/05/01']})
print(df)

          Date
0   1395/01/01
1   1395/02/01
2   1395/01/01
3   1395/05/01

解决方案:

print(df.loc[df['Date'].str.startswith('1395/01'), :])

          Date
0   1395/01/01
2   1395/01/01

如果你想提取所有行的年份和月份,你可以使用 str.slice:

df['Extracted Date'] = df['Date'].str.slice(0, 7)
print(df)

          Date  Extracted Date
0   1395/01/01         1395/01
1   1395/02/01         1395/02
2   1395/01/01         1395/01
3   1395/05/01         1395/05