【问题标题】:Python: Concatenate columns based on "\"Python:基于“\”连接列
【发布时间】:2019-02-04 18:20:51
【问题描述】:

我最近收到了一个来自数据库的 .csv 数据框,它本应返回 4 列,但实际上返回了 8 列。当我检查时,我发现添加了一些列,因为它看起来像是属于第四列有一个换行符。

换句话说,我看到的是这样的:

index  A  B    C         D      (extra)   (extra)  (extra)  (extra)
  0    1  2  'abc\'    'def\'    'ghi\'    'jkl\'   'xyz'   some_date
  1    1  2  'abc'    some_date
  2    1  2  'abc\'    'def'    some_date

与此相反:

index  A  B         C                D
  0    1  2  'abcdefghijklxyz'   some_date
  1    1  2       'abc'          some_date
  2    1  2     'abcdef'         some_date

有没有一种有效的方法来组合以换行符结尾的列和右侧的列?

【问题讨论】:

  • 您能否澄清“将以换行符结尾的列与右侧的列组合起来”?您能给我们看一个 CSV 样本吗?
  • 修复这样的 .csv 文件看起来很简单。您可以将 \' ' 替换为空。或者如果不知道空格的数量,你可以使用正则表达式'\ +'。我会使用 sed 预处理文件,或者只是在支持正则表达式的 gui 文本编辑器中进行替换,而不是使用 python。

标签: python newline concat string-concatenation


【解决方案1】:

第 1 步: 首先,您需要提取已拆分的列'D',并将其放在每行非空值的末尾。此外,'D' 中的每个值都应从其当前位置中删除。你可以用这样的循环来做到这一点:

import pandas as pd

D_col = []
for i,row in df.iterrows():
    # get the index of the last non-empty/null value in the row
    d_idx = next(j for j,x in reversed(list(enumerate(row))) if x)
    # put the value at that index in D_col
    D_col.append(row[d_idx])
    # replace that value with ''
    row.iloc[d_idx] = ''

这将从您的 DataFrame 中删除 some_date 值并将它们放入列表 D_col

第 2 步: 现在您可以使用str.replace 删除斜线并使用str.cat 加入列。这是一个例子:

from functools import reduce

columns_to_join = ['C', 'D', 'e1', 'e2', 'e3']
# first remove the slashes
cleaned_columns = [df[col].fillna('').str.replace('\\', '') for col in columns_to_join]

# create an empty Series to start reduce with
empty_series = pd.Series(['' for _ in range(len(df))])
# iterate over the cleaned columns and join them (using str.cat) into one column
C_col = reduce(lambda acc, col: acc.str.cat(col.fillna('')), cleaned_columns, empty_series)

第 3 步: 将所有这些整合到一个最终的 DataFrame 中。方法如下:

new_df = pd.DataFrame(df[['A', 'B']])
new_df['C'] = C_col
new_df['D'] = D_col

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 1970-01-01
    • 2022-01-20
    • 2017-02-10
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多