'Creating an If statement with multiple conditions in Power Bi
I have a table with a number of columns. I created a measure that counts how many days its been since the last entry was recorded.
| Location | Days since Last entry |
|---|---|
| Book | 10 |
| Hat | 4 |
| Dress | 9 |
| Shoe | 2 |
| Bag | 1 |
I want to create a column that shows the days since the last entry by group. (Red = 9+ days , Amber = 5+&9- days , Green = less than 4 days.
So far I tried
NewColumn=
IF (
[DaysSinceLastEntry] >= 9, "Red",
IF([DaysSinceLastEntry] < 9 && [DaysSinceLastEntry] >5 = "Amber",)
&
IF(
[DaysSinceLastEntry] <= 5, "Green"
))
The above gives something like:
| Location | Days since Last entry | Group |
|---|---|---|
| Book | 10 | Red |
| Book | 5 | Amber |
| Book | 2 | Green |
| Hat | 9 | Red |
| Hat | 5 | Amber |
| Hat | 2 | Green |
I want:
| Location | Days since Last entry | Group |
|---|---|---|
| Book | 10 | Red |
| Hat | 6 | Amber |
| Dress | 9 | Red |
| Shoe | 2 | Green |
| Bag | 1 | Green |
I cant figure out how to display the red/amber/green based on the number of days since the last entry. Doesn't have to be an if statement. Any help would be much appreciated, thank you.
Solution 1:[1]
Don't know if this is what you are looking for:
import pandas as pd
import plotly.graph_objs as go
# make dataframe
data = {
'Location': [
'Book',
'Hat',
'Dress',
'Shoe',
'Bag',
],
'DaysSinceLastEntry': [
10,
4,
9,
2,
1,
],
}
df = pd.DataFrame(data)
# assign color
def color_filter(x):
if x <= 5:
return '#00FF00' # green
elif 5 < x <= 9:
return '#FFBF00' # amber
else:
return '#FF0000' # red
df['Color'] = df.DaysSinceLastEntry.map(lambda x: color_filter(x))
# plot
fig = go.Figure(
go.Bar(x=df['Location'],
y=df['DaysSinceLastEntry'],
marker={'color': df['Color']})
)
fig.show()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CJR |
