我遇到了以下问题。我得到的数据格式对人眼来说很好,但对计算机而言却非常糟糕。例如,它具有表格格式,但没有分隔符,并且其标题是用文字包装的,这意味着如果它长于特定长度,则其余部分将写在新行上。
column 1 column 2 but column 3
with more text
1.5893001 1.513451 1.198420
1.5893001 1.513451 1.198420
1.5893001 1.513451 1.198420
1.5893001 1.513451 1.198420
etc...
我希望DataFrame中的列具有此标头具有的文本。我已经不得不通过手动将数据转换为字典来对数据进行预处理。
将此数据加载到DataFrame中之后,DataFrame的第一行是列标签,其中column2当然仅被部分读取。在第二行中,(第1列的)第一个值具有“”值,第二个值具有“具有更多文本”,而第三个值具有NaN。
我尝试过df.columns = df.iloc[0] + ' ' + df.iloc[1]
,这导致第二列具有正确的标签,而其他列具有nan
。
有没有条件表达式?
[编辑] @jezrael获取正确的格式
{0: {0: 'column 1', 1: '', 2: 1.5893001, 3: 1.5893001}
1: {0: 'column 2', 1: 'with more text', 2: 1.513451, 3: 1.513451}
2: {0: 'column 3', 1: None, 2: 1.198420, 3: 1.198420}}
答案 0 :(得分:1)
您可以用Series.fillna
替换misisng值,并用str.strip
删除对等空格,然后用iloc
删除前两行:
df.columns = (df.iloc[0] + ' ' + df.iloc[1].fillna('')).str.strip()
df = df.iloc[2:].reset_index(drop=True)
print (df)
column 1 column 2 with more text column 3
0 1.5893 1.51345 1.19842
1 1.5893 1.51345 1.19842