'pandas create a column with space based on the length of another column
I want to create a new column based on length.
test = pd.DataFrame({"col1": [7,5,3]})
test['space_word'] = f"{' ' * (test['col1'])} : left blank"
However, got error:
UFuncTypeError: ufunc 'multiply' did not contain a loop with signature matching types (dtype('<U21'), dtype('<U21')) -> dtype('<U21')
The desired output should be:
col1 space_word
7 : left blank
5 : left blank
3 : left blank
Solved:
Using transform()
test['space_word'] = test.col1.transform(lambda x: f"check {' ' * x} : left blank")
col1 space_word
0 7 check : left blank
1 5 check : left blank
2 3 check : left blank
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
