2017-04-11 108 views
1

我与下面的代码矩阵,并存储一定的数据在它连接多个列

df = [] 
r = 5000 
c = 50 
for i in xrange(r): 
    r = [''] * c 
    table.append(r) 

这样的矩阵如下所示:

0  1   2     3  4 5  6 7 ... 
3 NaN Nestlé  Africa   Import 
4 NaN Nutella Europe   Report 2010 to 2011 
5 Shell   USA    Revenues  2017  

由于每一行都有列数不均匀,我很困惑如何将所有列连接为一列,并最终删除不必要的空列,以便它看起来像这样

1 
3. Nestlé Africa Import 
4. Nutella Europe Report 2010 to 2011 
5. Shell USA Revenues 2017 
etc. 

如果在pandas.DataFrame(e.g. df2 = pd.DataFrame(df))中做到这一点比较容易,那么我也很好。

+0

我不确定数据来自哪里,为什么它会不均匀?使用''.join()方法可以很容易地连接,只是让我知道雀巢,非洲等数据来自何处以及为什么会不均匀 –

+0

嗨Abid,数据来自ocr'd pdf文档,给出这些结果的表格中长度不均匀。然而,这些结果是组成的,它只是代表我的问题 – Probs

+0

为什么你不能使用数组的长度来确定删除列的位置? –

回答

0

使用pandas,你可以加入像非空列:

代码:

df['concat'] = df.apply(lambda x: ' '.join(
    [unicode(y) for y in x if not pd.isnull(y)]), axis=1) 

测试代码:

import pandas as pd 
from io import StringIO 
df = pd.read_fwf(StringIO(u""" 
    0  1   2     3  4 5  6 
3 NaN Nestlé  Africa   Import 
4 NaN Nutella Europe   Report 2010 to 2011 
5 Shell   USA    Revenues  2017"""), 
    skiprows=0, header=1, index_col=0) 
print(df) 

df['concat'] = df.apply(lambda x: ' '.join(
    [unicode(y) for y in x if y and not pd.isnull(y)]), axis=1) 

print(df['concat']) 

结果:

 0  1  2   3  4  5  6 
3   Nestlé Africa Import     
4   Nutella Europe Report 2010 to 2011 
5 Shell    USA Revenues  2017  

3      Nestlé Africa Import 
4 Nutella Europe Report 2010.0 to 2011.0 
5     Shell USA Revenues 2017