pandas - 将字符串读入 pandas 数据帧时保留前导空格吗?

标签 pandas whitespace

我有一个 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/

相关文章:

html - SVG 空白和 CSS

python - 如何将 pandas.core.series.Series 转换为列表?

python - 从 Pandas 中的 read_csv 获取对象大小

python - 箱线图网格

python - 加快计算返回

python - 如何去除双空格并留下新行? Python

jsf - 在 h :selectOneRadio 的两个单选按钮之间添加空格

php - 文本区域在文本开头添加空格?

whitespace - 忽略 MediaWiki 空格

python - Pandas 在枢轴后调整数据框大小?