我正在try 将以下列转换为新行:

Id Prices
001 ["March:59", "April:64", "May:62"]
002 ["Jan:55", ETC]

id date price
001 March 59
001 April 64
001 May 62
002 Jan 55

The date:price pairs aren't s到red in a traditional dictionary format like the following solution:

Convert dictionary keys 到 rows and show all the values in single column using Pandas

I managed 到 get the key:value pairs in到 individual rows like:

Id Prices
001 March:59
001 April:64

And could split these in到 two columns using string manipulation but this feels inefficient instead of actually using the key:value pairs. Can anyone help please?

推荐答案

如果你有有效的列表,explodesplit:

df = pd.DataFrame({'Id': ['001', '002'],
                   'Prices':   [["March:59", "April:64", "May:62"], ["Jan:55"]]})

out = df.explode('Prices')
out[['date', 'price']] = out.pop('Prices').str.split(':', expand=True)

如果你有字符串,str.extractall和正则表达式和join:

df = pd.DataFrame({'Id': ['001', '002'],
                   'Prices':   ['["March:59", "April:64", "May:62"]', '["Jan:55"]']})

out = (df.drop(columns='Prices') 
          .join(df['Prices'].str.extractall(r'(?P<date>[^":]+):(?P<price>[^":]+)')
                .droplevel('match'))
       )

输出:

    Id   date price
0  001  March    59
0  001  April    64
0  001    May    62
1  002    Jan    55

regex demo次,第二次.

Python相关问答推荐

将数据框架与导入的Excel文件一起使用

如何使用根据其他值相似的列从列表中获取的中间值填充空NaN数据

如何更改分组条形图中条形图的 colored颜色 ?

优化器的运行顺序影响PyTorch中的预测

使用NeuralProphet绘制置信区间时出错

在嵌套span下的span中擦除信息

pandas:对多级列框架的列进行排序/重新排序

ruamel.yaml dump:如何阻止map标量值被移动到一个新的缩进行?

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

将一个双框爆炸到另一个双框的范围内

使用Python异步地持久跟踪用户输入

Pandas在rame中在组内洗牌行,保持相对组的顺序不变,

如何写一个polars birame到DuckDB

对数据帧进行分组,并按组间等概率抽样n行

多索引数据帧到标准索引DF

如何在Quarto中的标题页之前创建序言页

有没有一种方法可以根据不同索引集的数组从2D数组的对称子矩阵高效地构造3D数组?

如何在Polars中处理用户自定义函数的多行结果?

基于2级列表的Pandas 切片3级多索引

为什么在安装了64位Python的64位Windows 10上以32位运行?