python - Pandas:如何扩展包含列中具有不同键的字典的数据框行?

标签 python pandas

我有点卡住了,你能帮我解决一下吗?我将我面临的问题简化为以下内容:

输入

enter image description here

期望的输出

enter image description here

我知道如何处理 col 中的字典的情况。 c 具有相同的键。

最佳答案

您可以通过构造函数创建DataFrame,通过 stack reshape 最后join原文:

df1 = (pd.DataFrame(df.c.values.tolist())
         .stack()
         .reset_index(level=1)
         .rename(columns={0:'val','level_1':'key'}))
print (df1)
   key  val
0  c00  v00
0  c01  v01
1  c10  v10
2  c20  v20
2  c21  v21
2  c22  v22

df = df.drop('c', 1).join(df1).reset_index(drop=True)
print (df)
    a   b  key  val
0  a0  b0  c00  v00
1  a0  b0  c01  v01
2  a1  b1  c10  v10
3  a2  b2  c20  v20
4  a2  b2  c21  v21
5  a2  b2  c22  v22

关于python - Pandas:如何扩展包含列中具有不同键的字典的数据框行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853989/

相关文章:

python - 为什么 Pandas 和 Numpy 对与 NaN 的成对相关产生不同的结果?

python - 值错误: could not convert string to float in a CSV file

python - 如何将一列时间戳转换为日期时间?

python - MultiIndexing 行与 pandas DataFrame 中的列

python - 资源耗尽: OOM when allocating tensor only on gpu

python - 基于 Mac 的 Python GUI 库

python - 使用应用工厂的 Flask 应用找不到模板

python - 将此数据读入 pandas 数据框的优雅方法?

python - 如何根据另一个数据帧计算一个数据帧中的变量?

python - 如何使用 matplotlib 补丁绘制日历