I have a very wide df with about 100 columns, within which there are several 'XYZ_rating' columns that I want to pivot longer.
df = pd.DataFrame({
'id': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'first_rating': [1, 2, 3, 1, 2, 3, 1, 2, 3],
'second_rating': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
'third_rating': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9],
})
The df in question has about 100 other columns that I do not want to transform from wide to long. I also want to remove the '_rating' suffix from the the category string.
The solution I came up with didn't work and is roughly translated from my R background.
pd.melt(df, id_vars=str.contains('[^rating]'), value_vars=re.contains(`rating`), var_name='category', value_name='value')
Desired output df would look like:
id | category | rating | 100 other columns... |
---|---|---|---|
1 | first | 1 | ... |
1 | second | 2.8 | ... |
1 | third | 3.4 | ... |
... |