Posts

Showing posts with the label Loops

C#: Looping Through Lines Of Multiline String

Answer : I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this: string text = @"First line second line third line"; foreach (string line in new LineReader(() => new StringReader(text))) { Console.WriteLine(line); } Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's: using (StringReader reader = new StringReader(input)) { string line; while ((line = reader.ReadLine()) != null) { // Do something with the line } } This way you only have to test for nullity once, and you don't have to think about a do/while...

Concatenate Pandas DataFrames Generated With A Loop

Answer : Pandas concat takes a list of dataframes. If you can generate a list of dataframes with your looping function, once you are finished you can concatenate the list together: data_day_list = [] for i, day in enumerate(list_day): data_day = df[df.day==day] data_day_list.append(data_day) final_data_day = pd.concat(data_day_list) Exhausting a generator is more elegant (if not more efficient) than appending to a list. For example: def yielder(df, list_day): for i, day in enumerate(list_day): yield df[df['day'] == day] final_data_day = pd.concat(list(yielder(df, list_day)) Appending or concatenating pd.DataFrame s is slow. You can use a list in the interim and then create the final pd.DataFrame at the end with pd.DataFrame.from_records() e.g.: interim_list = [] for i,(k,g) in enumerate(df.groupby(['[*name of your date column here*'])): if i % 1000 == 0 and i != 0: print('iteration: {}'.format(i)) # just tells you where you are i...