Reputation: 477
I want to add a date column to data exported to csv file. Luckily the files are identified by the date they represent. However, I can't get the column to fill up with the appropriate user inputted value. Here's the code I have so far:
def read_file():
user_input = raw_input("Please put cost folder with date in form Costmm.dd: ")
path = r'C:\\Users\\CP\\documents\\' + user_input
allFiles = glob.glob(path + '/*.csv')
frame = pd.DataFrame()
frame['Date'] = pd.Series()
frame['Date'] = frame['Date'].astype(object).fillna(user_input)
list = []
for file in allFiles:
df = pd.read_csv(file,index_col=None,header=0)
list.append(df)
frame =pd.concat(list,ignore_index=True)
frame['Date'] = pd.Series()
return(frame)
Any and all help is greatly appreciated!
Upvotes: 0
Views: 41
Reputation: 394279
If I understand what you're after the following should work:
import datetime as dt
def read_file():
user_input = raw_input("Please put cost folder with date in form Costmm.dd: ")
path = r'C:\\Users\\CP\\documents\\' + user_input
allFiles = glob.glob(path + '/*.csv')
l = []
for file in allFiles:
df = pd.read_csv(file,index_col=None,header=0)
l.append(df)
frame =pd.concat(l,ignore_index=True)
frame['Date'] = dt.datetime.strptime(user_input, '%m.%d')
return frame
A few notes:
frame = pd.DataFrame()
frame['Date'] = pd.Series()
frame['Date'] = frame['Date'].astype(object).fillna(user_input)
The above was redundant as you overwrite this with the result of pd.concat
anyway.
Don't user list
for a variable name of type list
use something like df_list
.
To convert a string to datetime you can use dt.datetime.strptime
and pass the format string.
Upvotes: 1