Python Forum
A function to return only certain columns with certain string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A function to return only certain columns with certain string
#1
Hello,

I have this data set with 11 columns:

print(US_data)
Output:
Real_Personal_Income ... Retail_Sales_ExFood_YY Date ... 2000-01-31 10,856.0 ... - 2000-02-29 10,900.0 ... - 2000-03-31 10,929.0 ... - 2000-04-30 10,984.0 ... - 2000-05-31 11,022.0 ... - ... ... ... ... 2020-02-29 17,256.0 ... 4.4 2020-03-31 16,916.0 ... -2.6 2020-04-30 18,829.0 ... -15.3 2020-05-31 18,017.0 ... -1.1 2020-06-30 - ... 5.0
I'm trying to find/work out a function that can be used so that only the columns with 'YY' are returned. I assume it would be a if statement but I haven't been able to work it out.

Any help is appreciated.
Reply
#2
if US_data is a Pandas dataframe, you can filter columns by name, e.g.
cols_wanted = [col for col in US_data.columns if col.endswith('YY')]. Finally, you can select these columns, e.g. US_data[cols_wanted]. Probably, if 'YY' in col will be more suitable condition.
Reply
#3
(Jul-24-2020, 02:23 AM)scidam Wrote: if US_data is a Pandas dataframe, you can filter columns by name, e.g.
cols_wanted = [col for col in US_data.columns if col.endswith('YY')]. Finally, you can select these columns, e.g. US_data[cols_wanted]. Probably, if 'YY' in col will be more suitable condition.

Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Regex find string then return 10 character after it pyStund 6 1,499 Aug-04-2022, 11:26 PM
Last Post: Pedroski55
  Outputs "NaN" after "DataFrame columns" function? epsilon 7 3,573 Jan-27-2021, 10:59 AM
Last Post: epsilon
  Match string return different cell string Kristenl2784 0 1,399 Jul-20-2020, 07:54 PM
Last Post: Kristenl2784
  Apply function on different columns as defined DavidGG 6 4,961 Sep-04-2019, 03:35 PM
Last Post: vivekirti
  How to return values from For Loop via return in a function AykutRobotics 14 8,181 Jan-08-2019, 04:12 AM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020