1

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?

1 Answer 1

1

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}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I found my error. stack = df.join... and then: stack["Year"].value_counts().to_dict()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.