python - Pandas 将列重复到新行中

标签 python pandas csv

我在 csv 中有一些数据重复,我想创建多行来重复一些列。我正尝试在 Python 中使用 Pandas 来做到这一点。

将以下内容作为MWE。我使用 df = pandas.read_csv('my.csv') 导入我的数据,结果如下所示:

a  b  c  c.1  c.2
1  2  3   4    5
6  7  8   9    0

可以看出,列ab 是唯一的,但c 有多个值。我想将 c 值拆分成单独的行,复制 ab,即实现以下目标:

a  b  c
1  2  3
1  2  4
1  2  5
6  7  8
6  7  9
6  7  0

为了不必键入太多内容,我省略了一个类似重复的 d 列,但该解决方案应该足够通用以适应这种情况。

最佳答案

In [426]: pd.lreshape(df, {'c':df.columns[df.columns.str.match('^c\.?\d?')]})
Out[426]:
   a  b  c
0  1  2  3
1  6  7  8
2  1  2  4
3  6  7  9
4  1  2  5
5  6  7  0

关于python - Pandas 将列重复到新行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47127940/

相关文章:

python - 如何正确测试程序 python 脚本

python - 使用 Recorder 模块进行 Kivy 单元测试

python - pandas - 用大写字母替换字符串中的一个字母

python - 如何为 numpy genfromtxt 设置字符串到浮点转换器

python - 在 python 中重新格式化字典输出

python - 来自 Python 的 Microsoft Graph API 调用

Python 数组值在函数调用后意外更改

不同大小的 Python Pandas 细胞

python - 如何使用 Pandas Profiling 包仅生成相关性和散点图?

php - LOAD DATA INFILE - 显示导入的行数给出错误的值