Reputation:
My text file
Name Surname Age Sex Grade X
Chris M. 14 M 4 10 05 2010
Adam A. 17 M 11 12 2011
Jack O. M 8 08 04 2009
...
I want to count years. Example output: { '2010' : 1 , "2011" : 1 ...} but I got "Key Error : Year".
import pandas as pd
df = pd.read_fwf("file.txt")
df.join(df['X'].str.split(' ', 2, expand = True).rename(columns={0: '1', 1: '2', 2: '3}))
df.columns=["1"]
df["1"].value_counts().dict()
What's wrong with my code?
Upvotes: 1
Views: 1133
Reputation: 6556
Your df
will remain original one, you have to assign to it after you join with new column, then you will get the df
with column Year
. Try this:
import pandas as pd
df = pd.read_fwf("file.txt")
df = df.join(df['Date'].str.split(' ', 2, expand = True).rename(columns={1: 'Year', 0: 'Month'}))
df["Year"].value_counts().to_dict()
output:
{'2009': 1, '2010': 1, '2011': 1}
Upvotes: 1