![](/img/trans.png)
[英]How to overwrite a particular column of a csv file using pandas or normal python?
[英]Python: Extract a particular column(containing special characters) from csv file using pandas
我有一個文件(tests.txt)包含以下格式的數據:
NUMBER,\tFilename,\t\t\t\t\tTestName,\t\t\t\tConfig
001,\t\tFile1.csv,\t\tcube,\t\twidth height size
002,\t\tFile2.csv,\t\tsquare,\t\tlength param
通常看起來像:
HLM_TIER, Filename, TestName, Config
001, File1.csv, cube, width height size
002, File2.csv, square, length param
我想從此文件中提取特定列(TestName)。
import pandas as pd
data = pd.read_csv('tests.txt', skipinitialspace=True)
TestName = data.TestName
TestName = TestName.strip(' \t')
Traceback (most recent call last):
File "C:\Users\temp.py", line 23, in <module>
TestName = data.TestName
File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 2246, in __getattr__
(type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'TestName'
我認為錯誤是由於列中的選項卡導致pandas將列讀為“\\ t \\ t \\ t \\ t \\ t \\ t \\ TTestName \\”但是,我不確定,如何解決此問題。 注意:我無法更改“tests.txt”文件。
您可以使用converters
在讀取數據時去除數據。為此,您需要創建一個執行此剝離的函數,然后您需要將其傳遞到將列映射到函數的dict中。
您還應該使用names
參數手動指定列名稱並跳過標題行。
示例 -
def strip(x):
try:
return x.strip()
except AttributeError:
return x
col_names = ['HLM_TIER', 'Filename', 'TestName', 'Config', ...]
col_mapping = {key:strip for key in col_names}
data = pd.read_csv('tests.txt', names=col_names, converters=col_mapping)
你能刪除所有標簽嗎?
from StringIO import StringIO
with open('test.txt', 'r') as f:
df = pd.read_csv(StringIO(f.read().replace('\t', '')))
df.TestName
df = pd.read_csv('Foo.txt', delim_whitespace=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.