I’m trying to concatenate several csv files and create a ‘DATE_TIME’ column based on the specific column ‘NAME’. I apply an IF condition for extract the substring of DATE_TIME from NAME based on the appearance of a string ‘RE’.
Here’s my code:
JavaScript
x
38
38
1
import pandas as pd
2
import numpy as np
3
import os
4
5
path_dataset = r'C:Userstest'
6
7
def get_file(path_dataset):
8
files = os.listdir(path_dataset) #check file list
9
files.sort() #sort file
10
file_list = []
11
for file in files:
12
path = path_dataset + "\" + file
13
if (file.startswith("test")) and (file.endswith(".csv")):
14
file_list.append(path)
15
return (file_list)
16
17
read_columns = ['NAME']
18
19
read_files = get_file(path_dataset)
20
21
all_df = []
22
23
for file in read_files:
24
df = pd.read_csv(file, usecols = read_columns)
25
26
if (str(df['NAME'].astype(str).str[23:25]) == 'RE-'):
27
df['DATE_TIME'] = df['NAME'].astype(str).str[26:40]
28
else:
29
df['DATE_TIME'] = df['NAME'].astype(str).str[22:37]
30
31
all_df.append(df)
32
33
Concat_table = pd.concat(all_df, axis=0)
34
Concat_table = Concat_table.sort_values(['DATE_TIME'])
35
36
Concat_table.head()
37
Concat_table.to_csv(os.path.join(path_dataset, 'Concate_all.csv'), index=False)
38
My question is at the IF-ELSE statement. They return the same position of the substring, so that I get result below. This is not what I want, with the name ‘RE’ I still want to extract the date and time. What did I make a mistake for the code? Thank you.
Added my dataframe:
JavaScript
1
8
1
dic1 = {"NAME": ['1234567890-ABCDEFGHIJ-RE-20210802-194706',
2
'1234567890-ABCDEFGHIJ-20210801-200321']}
3
dic2 = {"NAME": ['1234567890-ABCDEFGHIJ-RE-20210731-050457',
4
'1234567890-ABCDEFGHIJ-20210801-122356']}
5
6
df1 = pd.DataFrame(dic1)
7
df2 = pd.DataFrame(dic2)
8
Advertisement
Answer
No need of IF statement. Split on – and concat the 2 last elements
EDIT
JavaScript
1
6
1
f = lambda x: (x["NAME"].split("-"))[-2] + "-" + (x["NAME"].split("-"))[-1].replace('.xlsx', '')
2
for file in read_files:
3
df = pd.read_csv(file, usecols = read_columns)
4
5
df['DATE_TIME'] = df.apply(f, axis=1)
6