【问题标题】:Merging data in a single pandas column based on criteria根据条件合并单个 pandas 列中的数据
【发布时间】:2017-04-06 01:36:48
【问题描述】:

我有一个包含大量数据的 pandas 数据框,如下所示:

temp_col
matt
joes\crabshack\one23
fail
joe:123,\
12345678,\
92313456,\
12341239123432,\
1321143
john
jacob
joe(x):543,\
9876544123,\
1234

如何获取以“,\”结尾的所有数据以及没有的其余行并将它们合并为一行?

预期输出:

temp_col
matt
joes\crabshack\one23
fail
joe:1231234567892313456123412391234321321143
john
jacob
joe(x):54398765441231234

【问题讨论】:

  • 这是 DataFrame 还是 Series 对象?
  • 这是一个包含多列的数据框,但这只是一列

标签: python regex python-3.x pandas


【解决方案1】:

你可以试试这个:

(df.temp_col.groupby((~df.temp_col.str.contains(r",\\$")).shift().fillna(True).cumsum())
 .apply(lambda x: "".join(x.str.rstrip(r",\\"))))

#temp_col
#1                                            matt
#2                            joes\crabshack\one23
#3                                            fail
#4    joe:1231234567892313456123412391234321321143
#5                                            john
#6                                           jacob
#7                        joe(x):54398765441231234
#Name: temp_col, dtype: object

分解

1) 创建一个组变量,当元素不以,\ 结尾时生成一个新组:

g = (~df.temp_col.str.contains(r",\\$")).shift().fillna(True).cumsum()
g
#0     1
#1     2
#2     3
#3     4
#4     4
#5     4
#6     4
#7     4
#8     5
#9     6
#10    7
#11    7
#12    7
#Name: temp_col, dtype: int64

2) 定义一个join 函数,去掉结尾的逗号和反斜杠;

join_clean = lambda x: "".join(x.str.rstrip(r",\\"))

3) 对每个组应用连接函数以连接以,\ 结尾的连续行:

df.temp_col.groupby(g).apply(join_clean)

#temp_col
#1                                            matt
#2                            joes\crabshack\one23
#3                                            fail
#4    joe:1231234567892313456123412391234321321143
#5                                            john
#6                                           jacob
#7                        joe(x):54398765441231234
#Name: temp_col, dtype: object

【讨论】:

    【解决方案2】:

    由于数据已包装(我假设您在其中看到此“\”,因此它是同一单元格的一部分。那么它只是一个逗号分隔的数字。

    df.columnnamehere.str.split(',').str.join(sep='')
    

    或者如果 '\' 是一个实际字符,而不仅仅是用于格式化

    df.columnnamehere.str.split(',\').str.join(sep='')
    

    【讨论】:

      【解决方案3】:

      我认为在将数据加载到 pandas DataFrame 之前(或何时)处理它会更好。但如果你坚持这样做,试试这个:

      from pandas import DataFrame
      df = DataFrame({'x': [
      'matt', 
      'joes\crabshack\one23',
      'fail',
      'joe:123,\\',
      '12345678,\\',
      '92313456,\\',
      '12341239123432,\\',
      '1321143',
      'john',
      'jacob',
      'joe(x):543,\\',
      '9876544123,\\'
      '1234']})
      df['g'] = (1 - df['x'].str.endswith('\\').astype(int).shift().fillna(0)).cumsum()
      df = df.groupby('g')['x'].sum().apply(lambda x: x.replace('\\', ''))
      df
      

      【讨论】:

        猜你喜欢
        • 2019-08-10
        • 2018-02-13
        • 2021-07-21
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多