I have this simple looking issue but can for the love the almighty not figure out how to solve it.
I have a data frame that has a column with strings. I can apply the code below to add a new column that shows how often the letter "a" occurs in the string next to it. Using a loop, I can do this with every word in the column.
What I want to do now is do the same thing for every letter in the alphabet by integrating my loop into another loop. So the end result should be a data frame with one column for each letter that shows the occurence of that letter in the string.
Loops inside loops really confuse me and while I can picture how it should work in theory, I have a hard time getting it to work in practice. :(
Thank you so much!
df = pd.DataFrame(["fancy","nice","aweseome","wow"])
A = []
for i in range(len(df)):
A.append(df.iloc[:, 0][i].count("a"))
df["A"] = A
df
EDIT:
Hey again friends, now I would like to apply the solution to as many string columns as there are in the df:
df = pd.DataFrame([["fancy", "cold"], ["nice","sunny"],["awesome", "warm"], ["wow", "rainy"]])
print(df)
for i in range(1,len(df.columns)):
for letter in ascii_lowercase:
df[letter] = df.iloc[:, i].apply(lambda x: x.lower().count(letter))
df.append(df)
print(df)
My code overwrites the a-z columns from the first string column. However, I would like that it adds separate a-z columns for each string column, if that makes sense.
If this messes with the order of variables in the data frame, then it could also be a solution to store the a-z output for each column in a new data frame (either one that is appended to or one for each column). I could not really get this to work either. :/
Any help? :) THX