Suppose a dataframe contains
attacker_1 attacker_2 attacker_3 attacker_4 Lannister nan nan nan nan Stark greyjoy nan
I want to create another column called AttackerCombo that aggregates the 4 columns into 1 column. How would I go about defining such code in python? I have been practicing python and I reckon a list comprehension of this sort makes sense, but [list(x) for x in attackers] where attackers is a numpy array of the 4 columns displays all 4 columns aggregated into 1 column, however I would like to remove all the nans as well. So the result for each row instead of looking like
starknannanlannisterwould look like
stark/lannister
I think you need
apply
withjoin
and removeNaN
bydropna
:If need
separator
empty string useDataFrame.fillna
:Another 2 solutions with
list comprehension
- first compare bynotnull
and second check ifstring
: