python - 仅当值不同时才创建新列
问题描述
我的数据框如下所示:
pd.DataFrame([["t1","d2","e3","r4"],
["t1","d2","e2","r4"],
["t1","d2","e1","r4"]],columns=["a","b","c","d"])
而且我要:
pd.DataFrame([["t1","d2","e3","r4","e1","e2"]],
columns=["a","b","c","d","c1","c2"])
即我只有一列值不同,我想创建一个新的数据框,并在观察到新值时添加列。是否有捷径可寻 ?
解决方案
编辑:概括任何单个非唯一列:
Ucols = df.columns[(df.nunique() == 1)].tolist()
df_out = df.set_index(Ucols).set_index(df.groupby(Ucols).cumcount(), append=True).unstack()
df_out.columns = [f'{i}{j}' if j != 0 else f'{i}' for i,j in df_out.columns]
print(df_out.reset_index())
输出:
a b d c c1 c2
0 t1 d2 r4 e3 e2 e1
原始答案
利用:
df_out = df.set_index(['a','b','d',df.groupby(['a','b','d']).cumcount()]).unstack()
df_out.columns = [f'{i}{j}' if j != 0 else f'{i}' for i,j in df_out.columns]
df_out.reset_index()
输出:
a b d c c1 c2
0 t1 d2 r4 e3 e2 e1
推荐阅读
- java - 未找到 maven-compiler-plugin
- javascript - 使用 JavaScript 访问 localStorage 数据
- swift - MapKit,手动设置当前位置?有可能的?
- ios - dyld_shared_cache_extract_dylibs 在 Xcode 10 和 iPhone XS 上失败,但在 iPhone 7 上有效
- ios - 与地图交互时的功能
- java - 通过其 REST 服务或通过 CLI 脚本连接到 Openshift 是最佳选择吗?
- python-3.x - 用户在python上输入正确输入时如何使计数增加
- r - 在绘图中重新排列 ggplot 轴组
- java - Java 是否有办法将变量名分配给 Scanner 类中的新对象?
- java - GSON - 将空值反序列化为“空”字符串