например. в Пандах -
Код: Выделить всё
import pandas as pd
df = pd.DataFrame({
'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],
'ht_one': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
'ht_two': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]
})
changed_df = pd.wide_to_long(df,
stubnames='ht',
i=['famid', 'birth'],
j='age',
sep='_',
suffix=r'\w+')
Изменить — добавлен код по мотивам Jqurious —
Код: Выделить всё
import pandas as pd
import numpy as np
import polars as pl
import re
# Create age group data
age_groups = np.random.choice(['0-18', '19-35', '36-50', '51-65', '65+'], size=10)
# Create gender data
genders = np.random.choice(['Male', 'Female', 'Other'], size=10)
# Create familiarity and affinity data
fam_aff = np.random.rand(10, 4)
# Create column names
cols = ['Age_group', 'Gender', 'Familiarity_loop1', 'Familiarity_loop2', 'Affinity_loop1', 'Affinity_loop2']
# Combine data into dataframe
data = np.column_stack([age_groups, genders, fam_aff])
df = pd.DataFrame(data=data, columns=cols)
df["unique_records"] = np.arange(len(df))
regex_pattern = '^.*_loop\d'
# get polars DF
pl_df = pl.from_pandas(df)
# get all columns list
col_list = pl_df.columns
loop_list = [] # list of columns which contains _loop
sans_loop_list = [] # list of columns which do not contain _loop
for col in col_list:
if re.search(regex_pattern, col):
loop_list.append(col)
else:
sans_loop_list.append(col)
pl_melt_df = (pl_df
.melt(
id_vars = pl_df.select(sans_loop_list).columns,
variable_name = "master_stack")
.with_columns(pl.col("master_stack").str.replace(r"_loop\d",""))
)
pl_melt_df.pivot(index=sans_loop_list, columns="master_stack", values="value")
Изменить 2 — добавлен вывод Polars и Вывод панд
Поляры -

< /p>
Вывод Pandas —

Подробнее здесь: https://stackoverflow.com/questions/759 ... -in-polars