Created
December 30, 2020 09:50
-
-
Save ash2shukla/99f6adac3c826595587350034210dccf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
def one_hot_column(df, column, labels, prefix=None, **kwargs): | |
dummies = pd.get_dummies(df[column], prefix=prefix or column, **kwargs) | |
for label in labels: | |
if f"{column}_{label}" not in dummies.columns: | |
dummies[f"{column}_{label}"] = 0 | |
return df.join(dummies) | |
if __name__ == "__main__": | |
import pandas as pd | |
df = pd.DataFrame({"x": list("aabc"), "y": [1, 2, 3, 4]}) | |
labels = list("abcd") | |
print(one_hot_column(df, "x", labels)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment