【问题标题】:Pandas: splitting text into two parts with unequal lengths熊猫:将文本分成长度不等的两部分
【发布时间】:2015-02-05 09:17:20
【问题描述】:

我正在寻找 pandas 中的子字符串功能:给定一系列位置,我想从每一行 i 中选择子字符串 [0:pos_i]

>>> text = pd.Series(['123456789', '987654321'])
0    123456789
1    987654321
dtype: object

>>> pos = pd.Series([3,6])
0    3
1    6
dtype: int64

输出应该是:

>>> pd.Series(['123', '987654'])
0    123
1    987654
dtype: object

在一个数据框中拆分成两列会更好:

>>> pd.DataFrame([['123', '456789'], ['987654', '321']])
        0       1
0     123  456789
1  987654     321

【问题讨论】:

  • 我的回答解决了你的问题吗?

标签: python string pandas substring


【解决方案1】:

对于仅分成两部分的简单情况:

tokens = []
for i, row in text.iteritems():
    tokens.append((row[:pos[i]], row[pos[i]:]))

df = pd.DataFrame(tokens) 

或者写成列表推导式:

df = pd.DataFrame([(row[:pos[i]], row[pos[i]:]) for i, row in text.iteritems()])

给予:

>>> df
        0       1
0     123  456789
1  987654     321

[2 rows x 2 columns]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多