Issue
This is my input data, which is stored in dataframe df.
Now i want to change all the values in column B to Yearly format. Here is my code:
D = []
for i in df['B']:
for j in df['C']:
if j == 'Year':
D.append(int(i)/1)
elif j == 'Month':
D.append(int(i)/12)
elif j == 'Day':
D.append(int(i)/365)
print(len(df))
print(len(D))
While my original df only has len of 10, the output (list D) has len of 100. Anyone knows how to fix the issue here?
Solution
Your code iterates 10 X 10 times because for each i of df['B'] it iterates throughout all the rows of df['C'].
https://pandas.pydata.org/docs/user_guide/basics.html#iteration
D = []
for row in df.itertuples():
if row.C == 'Year':
D.append(int(row.B)/1)
elif row.C == 'Month':
D.append(int(row.B)/12)
elif row.C == 'Day':
D.append(int(row.B)/365)
Answered By - Raibek
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.