python - 如何在 Pandas 中读取奇怪的 csv 文件?

标签 python csv pandas

我想阅读下面显示的示例 csv 文件

--------------
 |A|B|C| 
--------------
 |1|2|3| 
--------------
 |4|5|6| 
--------------
 |7|8|9| 
--------------

我试过了

pd.read_csv("sample.csv",sep="|")

但是效果不是很好。

如何读取此 csv?

最佳答案

您可以将参数 comment 添加到 read_csv然后通过 dropna 删除带有 NaN 的列:

import pandas as pd
import io

temp=u"""--------------
|A|B|C|
--------------
|1|2|3|
--------------
|4|5|6|
--------------
|7|8|9|
--------------"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="|", comment='-').dropna(axis=1, how='all')

print (df)
   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

更通用的解决方案:

import pandas as pd
import io

temp=u"""--------------
|A|B|C|
--------------
|1|2|3|
--------------
|4|5|6|
--------------
|7|8|9|
--------------"""
#after testing replace io.StringIO(temp) to filename
#separator is char which is NOT in csv
df = pd.read_csv(io.StringIO(temp), sep="^", comment='-')

#remove first and last | in data and in column names
df.iloc[:,0] = df.iloc[:,0].str.strip('|') 
df.columns = df.columns.str.strip('|')
#split column names
cols = df.columns.str.split('|')[0]
#split data
df = df.iloc[:,0].str.split('|', expand=True)
df.columns = cols
print (df)
   A  B  C
0  1  2  3
1  4  5  6
2  7  8  9

关于python - 如何在 Pandas 中读取奇怪的 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39462978/

相关文章:

Java OutputStreamWriter UTF-16 CVS StartLine 上的错误字符

python - 将 pandas 分组列转换为字符串时出错

python - 创建由另一列 pandas 分组的一列的排列

python - 在 Python 中数到 10 亿的最快方法

python - 使用 **kwargs 在 factory boy test 中调用函数

python - Pandas 时间序列数据第一次匹配后忽略 np.where

python - 如何统计每个单词在句子中出现的次数,得到每个句子的分数?

mysql - Pandas 导入未插入所有行

python - 按一列上的另一个数据框对数据框进行排序 - pandas

python - 连接数据帧单标签行选择返回多行