python - 通过字符串变量 reshape 数据框

标签 python pandas

我有一个数据框如下

df = pd.DataFrame({'a': ['aaa\nbbb\nccc','ddd\nfff\nggg'], 'b':[1,2]})
df

我想要得到

     a  b
0   aaa 1
1   bbb 1
2   ccc 1
3   ddd 2
4   fff 2
5   ggg 2

我知道如何在 R 中使用 library(reshape) 制作它,但我无法在 python 中找到模拟

>

最佳答案

用途:

df = (df.set_index('b')['a']
        .str.split('\n', expand=True)
        .stack()
        .reset_index(level=1, drop=True)
        .reset_index(name='a')
        .reindex(columns=df.columns))
print (df)
     a  b
0  aaa  1
1  bbb  1
2  ccc  1
3  ddd  2
4  fff  2
5  ggg  2

替代numpy:

s = df['a'].str.split('\n')
df = pd.DataFrame({'b':np.repeat(df['b'].values, s.str.len()),
                   'a':np.concatenate(s)})
print (df)
     a  b
0  aaa  1
1  bbb  1
2  ccc  1
3  ddd  2
4  fff  2
5  ggg  2

关于python - 通过字符串变量 reshape 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48490541/

相关文章:

python - Pandas 无法正确识别列

python - 如何在 python 中使用 yield 函数

python - SQLAlchemy 别名不是别名吗?

python - 通过计算乘积来总结 pandas DataFrame

python - 迭代 EOD .csv 以在每个文件中创建历史运行高点、低点

python - 绘制数据框中多列的带有误差条的条形图

python - 通过比较 Pandas 中前 n 行来获取列的最小值

Python 检查元组的相等性

python - 填充 Pandas Dataframe 中的货币缺失数据

python - 合并来自python中重复记录的信息