EXTRACTION METHOD OF MULTIPLE CONDITIONS

Asked 1 years ago, Updated 1 years ago, 313 views

  • If you want to extract January 1st

    df=df.query('date + area.str.contains('January 1')')
    
  • If you want to extract Tokyo on January 1st

    df=df.query('Date + Area.str.contains('January 1st.+Tokyo')')
    

If you want to extract January 1st

df=df.query('date + area.str.contains('January 1')')

If you want to extract Tokyo on January 1st

df=df.query('Date + Area.str.contains('January 1st.+Tokyo')')

What kind of code should I write if I want to extract Tokyo and Kanagawa on January 1st?

Enter a description of the image here

python pandas

2023-02-20 22:45

1 Answers

dfx=df[df['date + area'].str.contains(r'^January 1st_(?:Tokyo|Kanagawa)_')]
print(dfx)

add

If you change to Date and Area,

import pandas as pd

df = pd.DataFrame({
    Type: [1]*18,
    Date and Area: [
        'January 1st_Tokyo_Shinjuku', 'January 2nd_Tokyo_Shinjuku', 'January 3rd_Tokyo_Shinjuku',
        'January 1st_Tokyo_Hachioji', 'January 2nd_Tokyo_Hachioji', 'January 3rd_Tokyo_Hachioji',
        'January 1st_Kanagawa_Yokohama', 'January 2nd_Kanagawa_Yokohama', 'January 3rd_Kanagawa_Yokohama',
        'January 1st_Kanagawa_Fujisawa', 'January 2nd_Kanagawa_Fujisawa', 'January 3rd_Kanagawa_Fujisawa',
        'January 1st_Chiba_Chiba', 'January 2nd_Chiba_Chiba', 'January 3rd_Chiba_Chiba',
        'January 1st_Chiba_Ichikawa', 'January 2nd_Chiba_Ichikawa', 'January 3rd_Chiba_Ichikawa',
    ],
})

dfx=df.query('date and area.str.contains(r"^January 1st_(?:Tokyo|Kanagawa)_")')
print(dfx)

#    Type Date and Area
# 01 November 1st_Tokyo_Shinjuku
# 31 November 1st_Tokyo_Hachioji
# 61 November 1st_Kanagawa_Yokohama
# 91 November 1st_Kanagawa_Fujisawa


2023-02-20 23:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.