Add Several Columns to Pandas DataFrame Based on Existing Columns

Viewed 32

How can I label my x-axis with multiple columns? Here's an example that works:

df = pd.DataFrame({"player_name": ["Alan","Bob","Carl","Dan","Earl"],
                   "jersey_number": ['1','2','3','4','5'],
                   "hits" : [2,3,1,2,4],
                   "at_bats" : [7,6,8,7,8]
                  })
df["label"] = df["player_name"]+"-"+df["jersey_number"]
df.plot(x="label", y=["hits", "at_bats"])
plt.show()

But this has an couple weaknesses. First, the example line to create the label column is tedious. Second, string concat is finicky. If the jersey_numbers aren't strings (e.g. ints instead), the concat fails. I can write a subroutine to take a list of columns, cast all as strings, and concat them. That seems like it should be unnecessary though, that there should be some built-in way to do this, something like:

df = pd.DataFrame({"player_name": ["Alan","Bob","Carl","Dan","Earl"],
                   "jersey_number": ['1','2','3','4','5'],
                   "hits" : [2,3,1,2,4],
                   "at_bats" : [7,6,8,7,8]
                  })
df.plot(x=["player_name","jersey_number"], y=["hits", "at_bats"])
plt.show()

This doesn't work; it throws ValueError: x must be a label or position.

My googlefu hasn't been strong enough to discover the correct syntax. Does it exist, and if yes what is it? Thanks

1 Answers

One option is to set those column as index then plot:

df.set_index(["player_name","jersey_number"]).plot( y=["hits", "at_bats"])

which gives

enter image description here

Although I would prefer your first approach since it gives better representation:

df["label"] = df[["player_name","jersey_number"]].astype(str).agg('-'.join)

or

df['label'] = [f'{x}-{y}' for x,y in zip(df["player_name"],df["jersey_number"]) ]
Related