如何读取.txt文件并与.xlsx

时间:2019-05-24 03:32:50

标签: python pandas

我的myfile.txt文件很大(52,375 kb,ln 86213,18),如下所示

E.g

myfile.txt

  "Name"     "ID"   "School"            .                 .
  "steven"  "1212"  "harvard"          .                 .
  "michael" "9898"  "stanford"         .                 . 
     .      .      .
     .      .      .



In [1]
df1 = pd.read_csv("myfile.txt", sep = "\t", lineterminator = "\n")

Out [1]
           Name     ID  School            .                 .
  steven  1212  harvard          .                 .
  michael 9898  stanford         .                 . 
     .      .      .
     .      .      .

但是当我想与database.xlsx合并时,它不起作用。它只显示合并后数据框的标题

In [2]: df2 = pd.read_excel('Data Base Currency.xlsx')

Out [2]:
ID       status
1212     mechanical engineering
9898     electrical engineering

In [3]: df3 = pd.merge(df1,df2, on = "ID", how = "inner")

**and then my merge statement doesn't work**
Out [3]:
Name     ID  School   status

我的期望

  Name     ID                     School            .                 .
  steven  mechanical engineering  harvard          .                 .
  michael Electrical engineering  stanford         .                 . 
     .      .      .
     .      .      .

1 个答案:

答案 0 :(得分:0)

可能您的列具有不同的数据类型。 尝试运行此命令并告诉您发生了什么:

df1["ID"] = df1["ID"].astype(int)
df2["ID"] = df2["ID"].astype(int)
df3 = pd.merge(df1,df2, on = "ID", how = "inner")