我有一列填充了字符串值:
我希望能够创建另外两列,其中的字符串值已与第一列分开。我也想要一种有效的方法来做到这一点。
预期结果:
到目前为止,我一直在尝试矢量化,但尚未能够实现它。
对于分割部分,我解析行(使用 iterows,我知道必须尽可能避免 iterows。)并创建一个可用于填充新选项卡的列表,但在我看来,这方式太陈旧了。
另外,我怎样才能有效地修改每个单元格?例如添加逗号或对其进行操作?
谢谢。
最佳答案
使用str
访问器:
df = df.join(df['col_1'].astype(str).str.extract('(?P<col_2>\d{2})(?P<col_3>\d{3})'))
print(df)
# Output:
col_1 col_2 col_3
0 10500 10 500
1 25020 25 020
2 35640 35 640
3 45440 45 440
4 50454 50 454
5 62150 62 150
6 75410 75 410
或者简单几步:
df['col_1'] = df['col_1'].astype(str)
df['col_2'] = df['col_1'].str[:2]
df['col_3'] = df['col_1'].str[2:]
print(df)
# Output
col_1 col_2 col_3
0 10500 10 500
1 25020 25 020
2 35640 35 640
3 45440 45 440
4 50454 50 454
5 62150 62 150
6 75410 75 410
另一个例子:
df['col_1'] = df['col_1'].astype(str)
df['col_4'] = df['col_1'].str[:2] + '-' + df['col_1'].str[2:]
print(df)
# Output
col_1 col_4
0 10500 10-500
1 25020 25-020
2 35640 35-640
3 45440 45-440
4 50454 50-454
5 62150 62-150
6 75410 75-410
关于python - 如何根据列中字符串的索引拆分列,同时使用有效的方法解析所有 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70708495/