我想知道是否有更好的方法来解决以下问题
我有一个具有以下示例结构的数据框:
我希望使用一个值填充 sub_label,该值对应于在“_”字符上拆分 Split_key 中的值,并根据标签获取正确的元素。正确的元素是在唯一排序的标签数组中 label 中的值的索引,这些标签在 Split_key 中共享相同的值。
此处显示了正确的最终结果。
我最初的尝试在大型数据帧上非常慢:
for i,row in bigframe.iterrows():
duplicates=bigframe[ bigframe["Split_key"]==row["Split_key"]]
if len(row["Split_key"].split("_"))<1:
continue
if len(duplicates)==1:
row["sub_label"]=row["Split_key"].split("_")[0]
else:
try:
shift=sorted(duplicates["label"].unique().astype(int)).index(int(row["label"]))
except:
shift=0
if (shift<len(row["Split_key"].split("_"))):
row["sub_label"]=row["Split_key"].split("_")[shift]
有什么方法可以在 python/pandas 中向量化这段代码吗?我从上一篇文章中知道在 R 中使用 group/ungroup 可以实现这一点。
最佳答案
让我们尝试使用 groupby
和 factorize
然后使用 map
df['new'] = df.groupby('Split_key',as_index=False).apply(lambda x : pd.Series(x['label'].factorize()[0]).map(dict(enumerate(x['Split_key'].iloc[0].split('_'))))).values
df
Out[869]:
Split_key label sub_label new
0 A_B_C 7 NaN A
1 A_B_C 7 NaN A
2 A_B_C 8 NaN B
3 A_B_C 8 NaN B
4 A_B_C 10 NaN C
5 A_B_C 10 NaN C
6 D_E_F 2 NaN D
7 D_E_F 7 NaN E
8 D_E_F 15 NaN F
9 G_H_I 1 NaN G
10 G_H_I 2 NaN H
11 G_H_I 3 NaN I
关于pandas - 使用基于其他列 pandas 中的值的拆分和索引来处理一列中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72722941/