水平合并两个CSV文件

时间:2018-06-21 06:08:44

标签: python pandas concat

所以我有两个文本文件“ pt1.txt”和“ pt2.txt”

“ pt1.txt”的内容:

Name,ICO,Max,USD_ROI
Bitcoin,0.0,19535.7,N/A
Ethereum,0.0,1389.18,N/A
Ripple,0.0,3.6491,N/A
Bitcoin Cash,0.0,4091.7,N/A
EOS,0.99,21.4637,2068.05%
Cardano,0.0,1.27977,N/A
Stellar,0.0,0.851652,N/A

“ pt2.txt”的内容:

BTC_ROI,ETH_ROI
N/A,N/A
N/A,N/A
N/A,N/A
N/A,N/A
N/A,N/A
-260.77%,-130.75%
N/A,N/A
N/A,N/A

我想通过将“ pt2.txt”的内容添加到“ pt1.txt”中来组合“ pt1.txt”和“ pt2.txt”

这是我的代码:

import pandas as pd

f = open("pt1.txt","w+")
df = pd.read_csv("pt2.txt")
f.write(df["BTC_ROI"])
f.write(df["ETH_ROI"])

我这样说是错误的:

TypeError: write() argument must be str, not Series

如何更改代码,使“ pt1.txt”最终看起来像这样?

Name,ICO,Max,USD_ROI,BTC_ROI,ETH_ROI
Bitcoin,0.0,19535.7,N/A,N/A,N/A
Ethereum,0.0,1389.18,N/A,N/A,N/A
Ripple,0.0,3.6491,N/A,N/A,N/A
Bitcoin Cash,0.0,4091.7,N/A,N/A,N/A
EOS,0.99,21.4637,2068.05%,-260.77%,-130.75%
Cardano,0.0,1.27977,N/A,N/A,N/A
Stellar,0.0,0.851652,N/A,N/A,N/A

1 个答案:

答案 0 :(得分:1)

您正在尝试将列添加到现有CSV中。最简单的方法是将两个帧都读入存储器concat,然后转储它们。

df1 = pd.read_csv('pt1.txt')
df2 = pd.read_csv('pt2.txt')

(pd.concat([df1, df2], axis=1)
  .to_csv('pt2.txt', index=False, na_rep='N/A')
)

如果您的数据足够小,这是最简单的操作。