Click here to Skip to main content
16,015,414 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an array which I used np. loadtext on an csv file.


dataresale = np.loadtxt(resale,skiprows=1,usecols=(0,2,10),dtype=[('month','U50'),('flat_type','U50'),
('resale_price','f8')],delimiter=',')



print(dataresale['month'])


Below is the output


['2017-01' '2017-01' '2017-01' ... '2021-03' '2021-10' '2021-12']


I would like to only take out data from year 2021 (all months) only

Below is a script I used to take out rows by year in the another array, but this particular dataset has the months tagged to it


x= datap[datap['year']==2019]


Is there a way I can modify the script above to take out all 2021 data

What I have tried:

x= datap[datap['year']==2019]
Posted
Updated 2-Jan-22 3:35am
Comments
Richard MacCutchan 1-Jan-22 4:48am    
It is not clear what you are trying to do. If you can extract all the dates for 2019, then the same should hold true for 2021.
0x01AA 1-Jan-22 8:16am    
I don't know Python, but this ...
dates = ['2017-01', '2017-01', '2017-01', '2021-03', '2021-10', '2021-12']
years = [i for i in dates if i.startswith('2021') ]
print(years)

... prints ['2021-03', '2021-10', '2021-12']

And finally
monthsOfyear = [i[5:] for i in dates if i.startswith('2021-') ]

will give you only the months of 2021

1 solution

Provided, your example data
['2017-01' '2017-01' '2017-01' ... '2021-03' '2021-10' '2021-12']
is an array (and you simply forgot the commas) the following would extract the months for a give year

Python
dates = ['2017-01', '2017-01', '2017-01', '2021-03', '2021-10', '2021-12']
monthsOfYear =  [i[5:] for i in dates  if i.startswith('2021-') ]
print(monthsOfYear)

and output of the print will be:
['03', '10', '12']

I hope it helps.
 
Share this answer
 
v2
Comments
Richard MacCutchan 2-Jan-22 9:46am    
I think it is more complicated than that. The data is loaded using pandas/numpy, which creates tables, rather than simple arrays.
0x01AA 2-Jan-22 9:51am    
Thank you for the hint. Now I have to learn about Python tables :-)
Python does fascinate me more and more.

Do you think it is better to delete the answer?
Richard MacCutchan 2-Jan-22 10:05am    
Leave the answer, it may encourage OP to provide a better explanation.

I find Python quite fun also, once you get used to its crazy syntax.
0x01AA 2-Jan-22 13:18pm    
Thanks, so I will leave the answer.

For me (c++ programmer) just already only the python 'slice' stuff is great. And also the things what numpy supports is incredible. And the syntax basically I think is very ok (at least for me), only the thing with the indentations I hate ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900