Python:基于“连接列”\&引用;

Python:基于“连接列”\&引用;,python,newline,concat,string-concatenation,Python,Newline,Concat,String Concatenation,我最近从一个数据库收到一个.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

我最近从一个数据库收到一个.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
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] = ''
与此相反:

index  A  B         C                D
  0    1  2  'abcdefghijklxyz'   some_date
  1    1  2       'abc'          some_date
  2    1  2     'abcdef'         some_date
是否有一种有效的方法将以换行结尾的列与右侧的列组合在一起

第1步: 首先,您需要提取列
'D'
,该列已被拆分并放在每行非空值的末尾。此外,应将
'D'
中的每个值从其当前位置移除。您可以使用如下循环执行此操作:

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
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] = ''
这将从数据框中删除一些日期值,并将它们放入列表中

第二步: 现在,您可以使用
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)
第三步: 将所有这些合并到一个最终的数据帧中。以下是方法:

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

您能否澄清“将以换行结尾的列与右侧的列合并”?你能给我们看一个CSV的例子吗?修复这样的.CSV看起来很简单。您可以不使用任何内容替换\'。或者,如果不知道空间的数量,可以使用regexp'\+'。我将使用sed预处理文件,或者在支持regexp的gui文本编辑器中进行替换,而不是使用python。