这是另一种方式。由于您的原始数据框没有相同长度的列表(这将为您提供ValueError,您可以将其定义为:
data = {"id":[1,1,1,2,2,2,3,3,3],
"val": ["06123","nick","@gmail","06454","abey","@gmail","06888","sisi"],
"media": ["nrc","nrc","nrc","nrc","nrc","nrc","nrc","nrc"]}
df = pd.DataFrame.from_dict(data, orient="index")
df = df.transpose()
>>> df
id val media
0 1 06123 nrc
1 1 nick nrc
2 1 @gmail nrc
3 2 06454 nrc
4 2 abey nrc
5 2 @gmail nrc
6 3 06888 nrc
7 3 sisi nrc
8 3 NaN NaN
之后,您可以将np.nan 值替换为空字符串,这样您就可以groupby 您的id 列并将val 中的值以, 分隔。
df = df.replace(np.nan, "", regex=True)
df_new = df.groupby(["id"])["val"].apply(lambda x: ",".join(x)).reset_index()
>>> df_new
id val
0 1.0 06123,nick,@gmail
1 2.0 06454,abey,@gmail
2 3.0 06888,sisi,
然后,您只需将新的val 列拆分为 3 列,将其中的字符串拆分为您想要的任何方法。例如,
new_cols = df_new["val"].str.split(",", expand=True) # Good ol' split
df_new["kolom 1"] = new_cols[0] # Assign to new columns
df_new["kolom 2"] = new_cols[1]
df_new["kolom 3"] = new_cols[2]
df_new.drop("val", 1, inplace=True) # Delete previous val
df_new["media"] = "nrc" # Add the media column again
df_new = df_new.replace("", np.nan, regex=True) # If necessary, replace empty string with np.nan
>>> df_new
id kolom 1 kolom 2 kolom 3 media
0 1.0 06123 nick @gmail nrc
1 2.0 06454 abey @gmail nrc
2 3.0 06888 sisi NaN nrc