This question is an extension of Pandas conditional creation of a series/dataframe column . If we had this dataframe:
Col1 Col2
1 A Z
2 B Z
3 B X
4 C Y
5 C W
and we wanted to do the equivalent of:
if Col2 in ('Z','X') then Col3 = 'J'
else if Col2 = 'Y' then Col3 = 'K'
else Col3 = {value of Col1}
How could I do that?
Try this use np.where : outcome = np.where(condition, true, false)
df["Col3"] = np.where(df['Col2'].isin(['Z','X']), "J", np.where(df['Col2'].isin(['Y']), 'K', df['Col1']))
Col1 Col2 Col3
1 A Z J
2 B Z J
3 B X J
4 C Y K
5 C W C
A simple (but likely inefficient) way can be useful when you have multiple if condition. Like you are trying to put values into (say) four buckets based on quartiles.
df holds your data, col1 has the values, col2 should have the bucketized values (1,2,3,4) quart has the 25%, 50% and 75% bounds. try this
You can find the quartiles via A = df.describe() and then print(A[col1])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.