gpt4 book ai didi

python - 根据字符串位置将 Pandas 系列分成多个 DataFrame 列

转载 作者:行者123 更新时间:2023-11-28 22:16:05 25 4
gpt4 key购买 nike

给定一个带有字符串的 Pandas Series,我想创建一个 DataFrame,其中包含基于位置的 Series 的每个部分的列.

例如,给定这个输入:

s = pd.Series(['abcdef', '123456'])
ind = [2, 3, 1]

理想情况下我会得到这个:

target_df = pd.DataFrame({
'col1': ['ab', '12'],
'col2': ['cde', '345'],
'col3': ['f', '6']
})

一种方法是逐个创建它们,例如:

df['col1'] = s.str[:3]
df['col2'] = s.str[3:5]
df['col3'] = s.str[5]

但我猜这比单次拆分要慢。

我尝试了一个正则表达式,但不确定如何解析结果:

pd.DataFrame(s.str.split("(^(\w{2})(\w{3})(\w{1}))"))
# 0
# 0 [, abcdef, ab, cde, f, ]
# 1 [, 123456, 12, 345, 6, ]

最佳答案

你的正则表达式就差不多了(注意 Series.str.extract(expand=True) 返回一个 DataFrame):

df = s.str.extract("^(\w{2})(\w{3})(\w{1})", expand = True)
df.columns = ['col1', 'col2', 'col3']
# col1 col2 col3
# 0 ab cde f
# 1 12 345 6

这里有一个概括这个的函数:

def split_series_by_position(s, ind, cols):
# Construct regex.
regex = "^(\w{" + "})(\w{".join(map(str, ind)) + "})"
df = s.str.extract(regex, expand=True)
df.columns = cols
return df

# Example which will produce the result above.
split_series_by_position(s, ind, ['col1', 'col2', 'col3'])

关于python - 根据字符串位置将 Pandas 系列分成多个 DataFrame 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52432051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com