【发布时间】:2014-06-14 11:01:51
【问题描述】:
我是merging 两个 CSV 文件,下面有输入。
file1.csv
Id,attr1,attr2,attr3
1,True,7,"Purple"
2,False,19.8,"Cucumber"
3,False,-0.5,"A string with a comma, because it has one"
4,True,2,"Nope"
5,True,4.0,"Tuesday"
6,False,1,"Failure"
file2.csv
Id,attr4,attr5,attr6
2,"python",500000.12,False
5,"program",3,True
3,"Another string",-5,False
当我运行这段代码时
import pandas as pd
df1 = pd.read_csv("file1.csv")
df2 = pd.read_csv("file2.csv")
merged = df1.merge(df2, on="Id", how="outer").fillna("")
merged.to_csv("merged.csv", index=False)
我得到这样的输出
Id,attr1,attr2,attr3,attr4,attr5,attr6
1,True,7.0,Purple,,,
2,False,19.8,Cucumber,python,500000.12,False
3,False,-0.5,"A string with a comma, because it has one",Another string,-5.0,False
4,True,2.0,Nope,,,
5,True,4.0,Tuesday,program,3.0,True
6,False,1.0,Failure,,,
请注意,我的几条记录中的attr2 已从int 转换为float。
1,True,7.0,Purple,,,
与预期相比
1,True,7,Purple,,,
对于这个示例数据集,这是一个小麻烦。但是,当我针对我的大量数据运行它时,我的Id 列上也会发生这种行为。这将进一步打破我的工作流程链。
如何防止 pandas 对整个文件或理想情况下对特定列进行这种转换?
【问题讨论】: