我遇到了以下问题。我的数据格式很好,适合人眼阅读,但计算机阅读起来却很糟糕。例如,它有一个表格格式但没有分隔符,并且它的标题是自动换行的,这意味着如果它的长度超过特定长度,其余部分将另起一行。
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 中的列具有此 header 所具有的文本。我已经对必须通过手动将数据转换为字典来预处理数据这一事实感到恼火。
将此数据加载到 DataFrame 后,DataFrame 的第一行是列标签,其中 column2 当然只被部分读取。在第二行中,第一个值(第 1 列)的值为 '',第二个值为 'with more text',第三个值为 NaN。
我已经尝试过 df.columns = df.iloc[0] + ' ' + df.iloc[1] 这导致第二列具有正确的标签,但其他列具有 南。
有没有办法做一个条件表达式?
[编辑] @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}}
请您参考如下方法:
您可以用 Series.fillna 替换缺失值adn 通过 str.strip 删除尾随空格,然后使用 iloc 删除前 2 行:
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
