map_one_column_to_another
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
map_one_column_to_another [2022/12/19 22:20] – created raju | map_one_column_to_another [2022/12/19 22:46] (current) – [map one series to another in a case insensitive manner] raju | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ==== map one series to another in a case insensitive manner ==== | ||
+ | |||
+ | Given two dataframes | ||
+ | < | ||
+ | df1 | ||
+ | Item Team | ||
+ | 0 jetties | ||
+ | 1 Jetty Team_2 | ||
+ | 2 Joint use Team_1 | ||
+ | |||
+ | df2 | ||
+ | Item | ||
+ | 0 Jetty | ||
+ | 1 Jetties | ||
+ | 2 Joint use | ||
+ | </ | ||
+ | |||
+ | map df2[' | ||
+ | |||
+ | Expected output (if case is included): | ||
+ | < | ||
+ | Item Team_include_case | ||
+ | 0 Jetty Team_2 | ||
+ | 1 Jetties | ||
+ | 2 Joint use Team_1 | ||
+ | </ | ||
+ | |||
+ | Expected output (if case is ignored): | ||
+ | < | ||
+ | Item Team_ignore_case | ||
+ | 0 Jetty | ||
+ | 1 Jetties | ||
+ | 2 Joint use | ||
+ | </ | ||
+ | |||
+ | Solution: | ||
+ | < | ||
+ | % cat 72994107_v4.py | ||
+ | import pandas as pd | ||
+ | |||
+ | df1 = pd.DataFrame({ | ||
+ | " | ||
+ | " | ||
+ | }) | ||
+ | print(" | ||
+ | print(df1) | ||
+ | |||
+ | df2 = pd.DataFrame({" | ||
+ | print(" | ||
+ | print(df2) | ||
+ | |||
+ | |||
+ | def map_series(s, | ||
+ | if ignore_case: | ||
+ | result = s.str.lower().map( | ||
+ | df.assign(**{key_col: | ||
+ | .set_index(key_col)[value_col] | ||
+ | ) | ||
+ | else: | ||
+ | result = s.map(df.set_index(key_col)[value_col]) | ||
+ | return result | ||
+ | |||
+ | |||
+ | df2[" | ||
+ | df2[" | ||
+ | ) | ||
+ | df2[" | ||
+ | df2[" | ||
+ | ) | ||
+ | print(" | ||
+ | print(df2) | ||
+ | </ | ||
+ | |||
+ | Sample run: | ||
+ | < | ||
+ | % python 72994107_v4.py | ||
+ | df1 | ||
+ | Item Team | ||
+ | 0 jetties | ||
+ | 1 Jetty Team_2 | ||
+ | 2 Joint use Team_1 | ||
+ | df2 | ||
+ | Item | ||
+ | 0 Jetty | ||
+ | 1 Jetties | ||
+ | 2 Joint use | ||
+ | after mapping | ||
+ | Item Team_include_case Team_ignore_case | ||
+ | 0 Jetty Team_2 | ||
+ | 1 Jetties | ||
+ | 2 Joint use Team_1 | ||
+ | </ | ||
+ | |||
+ | Ref: | ||
+ | * https:// | ||
+ | * https:// | ||
+ | |||
+ | {{tag> | ||
==== map one column to another ==== | ==== map one column to another ==== | ||
< | < |
map_one_column_to_another.1671488401.txt.gz · Last modified: 2022/12/19 22:20 by raju