拆分/提取系列索引中的字符串并作为DataFram展开

2024-03-29 10:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫系列如下:

index      Value
'4-5-a'     2
'6-7-d'     3
'9-6-c'     7
'5-3-k'     8

我想提取/拆分序列的索引,并形成如下所示的数据帧:

index      Value   x    y
'4-5-a'     2      4    5
'6-7-d'     3      6    7
'9-6-c'     7      9    6
'5-3-k'     8      5    3

最好的方法是什么?你知道吗


Tags: 数据方法indexvalue序列
1条回答
网友
1楼 · 发布于 2024-03-29 10:28:24

这是一种方法。你知道吗

# convert series to dataframe, elevate index to column
df = s.to_frame('Value').reset_index()

# split by dash and exclude final split
df[['x', 'y']] = df['index'].str.split('-', expand=True).iloc[:, :-1].astype(int)

print(df)

   index  Value  x  y
0  4-5-a      2  4  5
1  6-7-d      3  6  7
2  9-6-c      7  9  6
3  5-3-k      8  5  3

相关问题 更多 >