python - 如果存在特定模式(例如数字然后字母),如何将数据透视表应用于数据框列?

标签 python python-3.x pandas python-2.7 pivot-table

我正在尝试在Python3中编写代码以将第一个表转换为预期的表。 您能帮我把我现有的转换成底部预期的吗?

当前一个:

1104369592
MA01609Worcester
MA01604Worcester
MA01604Worcester
1104842379
MA01040Hampden
MA01040Hampden
1104896613
MA02745Bristol
MA02745Bristol

预期的一个:

1104469592 MA01609Worcester
1104469592 MA01609Worcester
1104469592 MA01609Worcester
1104842379 MA01040Hampden
1104842379 MA01040Hampden
1104896613 MA02745Bristol
1104896613 MA02745Bristol

我没有找到任何解决方案。我尝试过旋转,但我不知道该怎么做。

最佳答案

可能不是最干净的,但它可以工作:

import pandas as pd

current = pd.Series([
    "1104369592",
    "MA01609Worcester",
    "MA01604Worcester",
    "MA01604Worcester",
    "1104842379",
    "MA01040Hampden",
    "MA01040Hampden",
    "1104896613",
    "MA02745Bristol",
    "MA02745Bristol"
])

def get_subframe(x):
    return pd.DataFrame({
        "num": x.iloc[0],
        "val": x.iloc[1:]
    })

groups = s.str.isnumeric().cumsum()
out = s.groupby(groups).apply(get_subframe).reset_index(drop=True)

输出:

          num               val
0  1104369592  MA01609Worcester
1  1104369592  MA01604Worcester
2  1104369592  MA01604Worcester
3  1104842379    MA01040Hampden
4  1104842379    MA01040Hampden
5  1104896613    MA02745Bristol
6  1104896613    MA02745Bristol

关于python - 如果存在特定模式(例如数字然后字母),如何将数据透视表应用于数据框列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74918149/

相关文章:

python - 在 Python 中打印继承的类

python - 对于 X 秒,每 Y 秒做一些 Action

python - 更改 numpy 数组中字符串的位置

python - 在多索引 Groupby 对象中填充 Nan 值

python - 如何避免解码为 str : need a bytes-like object error in pandas?

python - 如何从jupyter笔记本导出清理后的数据,而不是原始数据

python - 类型对象 'datetime.datetime' 没有属性 'fromisoformat'

Python lrparsing模块;无法解析简单的递归文法

python - urllib 下载的文件与我手动下载的文件不同

python - 使用 Python 3 打印不带括号的不同错误消息