use*_*266 0 import text pandas
我正在尝试将文本文件读入熊猫,但它为所有行创建了 NaN。我尝试使用分隔符来分解由 \ 分隔的变量,但这无法正常工作。这是数据文件在文本文件中的样子
数据:
Date         Name          Group    Direction
2015-01-01  Smith.John      -          In
2015-01-01  Smith.Jan       Claims     Out
2015-01-01     -            Claims     In
2015-01-01  Smith.Jessica   Other      In
这是我第一次尝试读入数据:
pd.read_csv('C:\Users\Desktop\skills.txt',
        names=['Date','AgentName','Group','Direction'])
然而,这种产
    Date    AgentID     AssignedWorkGroup   CallDirection
 0  Date\tAgentID\tAssignedWorkGroup\tCallDire...   NaN     NaN     NaN
 1  2015-09-01\Smith.John\t-\tIn                    NaN     NaN     NaN
所以我试图通过执行以下操作来摆脱 \:
 pd.read_csv('C:\Users\Desktop\skills.txt',
         names=['Date','AgentName','Group','Direction'],delimiter='\\')
但这仍然会产生相同的结果。所以有几件事。一是我不能打破'\'。此外,看起来读入的第一行是标题。我尝试使用 header=None 来摆脱它们,但这对我来说也不是很好。似乎他们在(我假设是文本?)被放置在每个变量的前面
我觉得好像我在错误地接近这个
因为您传递了备用列名,这意味着 csv 解析器将第一行解释为有效的数据行,因此您需要传递skiprows=1以跳过标题,另外默认分隔符是逗号,,但看起来您的数据是制表符或多行- 空格分隔,因此您可以通过sep='\t'或sep='\s+'。
目前尚不清楚您的数据是制表符还是空格分隔,但以下内容对我有用:
In [18]:
t="""Date         Name          Group    Direction
2015-01-01  Smith.John      -          In
2015-01-01  Smith.Jan       Claims     Out
2015-01-01     -            Claims     In
2015-01-01  Smith.Jessica   Other      In"""
pd.read_csv(io.StringIO(t), names=['Date','AgentName','Group','Direction'], skiprows=1, sep='\s+')
Out[18]:
         Date      AgentName   Group Direction
0  2015-01-01     Smith.John       -        In
1  2015-01-01      Smith.Jan  Claims       Out
2  2015-01-01              -  Claims        In
3  2015-01-01  Smith.Jessica   Other        In
所以我期待
pd.read_csv('C:\Users\Desktop\skills.txt', names=['Date','AgentName','Group','Direction'], skiprows=1, sep='\t')
或者
pd.read_csv('C:\Users\Desktop\skills.txt', names=['Date','AgentName','Group','Direction'], skiprows=1, sep='\s+')
为你工作
| 归档时间: | 
 | 
| 查看次数: | 17914 次 | 
| 最近记录: |