You're very close — the row-order breakage is coming from a couple of small pandas behaviours. Short summary first, then a drop-in fixed function and a few notes.
Why it gets reordered
groupby(...).agg(...) sorts group keys by default (sort=True), so your groups (and therefore rows in the result) are returned in sorted order, not the original appearance order.
Converting discussion to a categorical and using cat.codes can assign numeric codes in an order you don't expect (category ordering can differ from original appearance).
Minor: you set a custom df.index then call to_csv(..., index=False), so that index is discarded in the output (probably not what you intended).
df.apply(...) to build the index is slow — use vectorized string operations instead.
Fixed / improved implementation
This preserves the input order of groups (use sort=False), creates d_id in order of first appearance using pd.factorize, and is vectorized / faster:
pythonCopy codeimport pandas as pd
def prepare_du_data():
df = load_general_data("/home/esther/PycharmProjects/Dialogos/processing_data/all_annotated_data_2025-08-05.csv")
# If you need a specific intra-group order for the joined text (e.g. by original row order or by 'turn'), sort here:
# df = df.sort_values(["discussion", "turn", "author"])
# group without sorting groups; return a flat dataframe (as_index=False)
df = df.groupby(
['discussion', 'author', 'turn', 'du_id'],
sort=False,
as_index=False
).agg(text=("text", " ".join))
# contribution id per discussion in the current (grouped) order
df["cont_id"] = df.groupby("discussion").cumcount() + 1
# assign discussion numeric ids in order of first appearance (pd.factorize preserves appearance order)
df["d_id"] = pd.factorize(df["discussion"])[0] + 1
# faster, vectorized index
df.index = df["d_id"].astype(str) + "_" + df["cont_id"].astype(str)
final_cols = ["discussion", "d_id", "cont_id", "author", "turn", "du_id", "text"]
# if you want that index to appear as a column in the CSV:
df.reset_index(inplace=True) # moves the index into a column named like 'index'
df.rename(columns={"index": "d_cont_index"}, inplace=True)
df[["d_cont_index"] + final_cols].to_csv("../data/du_all_contributions.csv", index=False)
# OR if you prefer to keep index as index in the file:
# df[final_cols].to_csv("../data/du_all_contributions.csv", index=True)
Extra notes / options
If you want groups sorted deterministically (e.g., by turn) before concatenating text, explicitly call df.sort_values(...) before the groupby. Otherwise the concatenation order inside .join() may be the original row order (or whatever order the DataFrame currently has).
If you do want alphabetical/numerical ordering of discussion for d_id, then astype("category").cat.codes is OK; otherwise use pd.factorize(...) to preserve first-seen order.
Use as_index=False in groupby to avoid reset_index() roundtrip.
Avoid .apply(lambda ...) on rows for string building — it's slow. Vectorized concatenation as shown is better.
If you want, tell me the exact ordering you expect (e.g. "preserve original file order", or "order by discussion → turn → author"), and I’ll give the exact sort_values call to guarantee that order before grouping.