我有一个 csv,我正在尝试将其加载到 pandas 中。 csv 中有三列,由管道分隔。前 2 列是整数,第三列是字符串。数据中存在不规则之处,例如某些字符串以空格开头,而有些字符串则不然。我所处的情况是,我必须保留那些前导空格以供后续处理步骤使用,但是,pandas 似乎将其剥离。任何帮助将不胜感激!
示例数据:
1|2|Dogs are better than cats!
1|4| Cats are superior to dogs.
2|3|Birds Rule. More than you think! #birdsrule
2|10|Birds birds birds
我尝试了 read_csv 函数并构建了自己的解析器,但均无济于事。以下是我的尝试:
读取_csv:
my_df=pd.read_csv("foo.txt", sep="|", dtype=str, names=['num1','num2','some_Text'], encoding = 'utf8', skipinitialspace=False)
我自己的解析器:
my_df = []
with open("foo.txt", "r") as data:
for row in data:
num1, num2, some_text = row.split("|")
some_text = some_text.strip("\n")
my_df.append(
pd.DataFrame({
"num1": [num1],
"num2": [num2],
"some_text": [some_text]
})
)
my_df = pd.concat(my_df)
最佳答案
您的代码应该可以正常工作。
In [17]: df = pd.read_csv("foo.txt", sep="|", dtype=str, names=['num1','num2','some_Text'], encoding = 'utf8', skipinitialspace=False)
In [18]: df
Out[18]:
num1 num2 some_Text
0 1 2 Dogs are better than cats!
1 1 4 Cats are superior to dogs.
2 2 3 Birds Rule. More than you think! #birdsrule
3 2 10 Birds birds birds
In [19]: df.values
Out[19]:
array([['1', '2', 'Dogs are better than cats!'],
['1', '4', ' Cats are superior to dogs.'],
['2', '3', 'Birds Rule. More than you think! #birdsrule'],
['2', '10', 'Birds birds birds']], dtype=object)
请注意,Cats 之前的空格被保留,但由于字符串列是右对齐的,因此您可能会误以为不是这样。
In [24]: df["some_Text"][1]
Out[24]: ' Cats are superior to dogs.'
它也应该工作,并通过更简单的调用适本地处理类型(我的意思是让 num1 和 num2 成为整数),即 pd.read_csv("foo.txt", sep="|", names =['num1','num2','some_Text'])
.
关于pandas - 将字符串读入 pandas 数据帧时保留前导空格吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43081304/