无法使用Pandas从CSV标头中删除白色

lx0bsm1f  于 2023-05-26  发布在  其他
关注(0)|答案(4)|浏览(92)

我正在尝试重命名csv中白色的标题。使用Pandas API参考中的这些行不起作用。标题仍然有白色而不是下划线。

import pandas as pd

df = pd.read_csv("my.csv",low_memory=False)
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_')
bwleehnv

bwleehnv1#

尝试使用列表理解。

df.columns = [c.strip().lower().replace(' ', '_') for c in df.columns]
z9gpfhce

z9gpfhce2#

尝试使用重命名?

df.rename(index=str, columns={"A space": "a", "B space ": "c"})
h43kikqp

h43kikqp3#

我抛弃了Pandas,只使用了Python 2.7中的CSV模块。

import csv
import re
import tempfile
import sys
import os
if sys.version_info >= (3, 3):
    from os import replace
elif sys.platform == "win32":
    from osreplace import replace
else:
    from os import rename as replace

newHeaderList = []

with tempfile.NamedTemporaryFile(dir='.', delete=False) as tmp, \
    open('myFile.txt', 'rb') as f:
    r = csv.reader(f, delimiter = '\t')
    w = csv.writer(tmp, delimiter = '\t', quoting=csv.QUOTE_NONNUMERIC)
    header = next(r)
    for h in header:
        headerNoSpace = re.sub("\s+", "_", h.strip())
        newHeaderList.append(headerNoSpace)
    w.writerow(newHeaderList)
    for row in r:
        w.writerow(row)

os.rename(tmp.name, new_text_filepath)

new_txt = csv.reader(open('newFile.txt', "rb"), delimiter = '\t')
out_csv = csv.writer(open('myFile.csv', 'wb'))
out_csv.writerows(new_txt)
hujrc8aj

hujrc8aj4#

你可以使用regex作为sep来删除头中的所有空格:

import pandas as pd
df = pd.read_csv("example.csv", sep='\s*&\s*')

这里\s表示一个空白字符,*表示匹配前面的表达式(这里是\s)零次或任意次。
我猜你正在阅读一个像这样的文件

Name,  Age,   City
John Smith, 30, New York
Jane Doe, 25, San Francisco
Bob Johnson, 45, Los Angeles

或者像这样

Name        , Age , City
John Smith  , 30  , New York
Jane Doe    , 25  , San Francisco
Bob Johnson , 45  , Los Angeles

两者都可以使用上面的代码。但是,在sep中使用正则表达式可能会减慢阅读过程,因为'c'引擎不支持正则表达式,因此将使用'python'引擎。阅读非常大的文件时要小心。

相关问题