场景
我有 2 个 CSV 文件(1)u.Data 和(2)prediction_matrix,我需要将其读取并写入单个数据帧,完成后将根据 int/float 进行聚类处理它将包含的值
问题
我已将 2 个 CSV 合并为 1 个名为 AllData.csv 的 Dataframe,但保存值的列类型现在具有不同的类型 (对象),如下所示如下所示(带有警告)
sys:1: DtypeWarning: Columns (0,1,2) have mixed types. Specify dtype option on import or set low_memory=False.
UDATA -------------
uid int64
iid int64
rat int64
dtype: object
PRED_MATRIX -------
uid int64
iid int64
rat float64
dtype: object
AllDATA -----------
uid object
iid object
rat object
dtype: object
附注我知道如何使用 low_memory=False
并且这只会抑制警告。
可能的原因
with open('AllData.csv', 'w') as handle:
udata_df.to_csv(handle, index=False)
pred_matrix.to_csv(handle, index=False)
因为,我需要将 2 个 CSV 写入使用的单个 DF handle 对象,并且可能会将所有值转换为其类型。任何东西都可以保留应用相同逻辑的数据类型吗?
到目前为止无用的引用资料:
最佳答案
第二个DataFrame
中的 header 写入也有问题,因此需要参数header=False
:
with open('AllData.csv', 'w') as handle:
udata_df.to_csv(handle, index=False)
pred_matrix.to_csv(handle, index=False, header=False)
另一个解决方案是附加第二个DataFrame
的mode=a
:
f = 'AllData.csv'
udata_df.to_csv(f, index=False)
pred_matrix.to_csv(f,header=False, index=False, mode='a')
或者使用concat
:
f = 'AllData.csv'
pd.concat([udata_df, pred_matrix]).to_csv(f, index=False)
示例:
udata_df = pd.DataFrame({'uid':[1,2],
'iid':[8,9],
'rat':[0,3]})
pred_matrix = udata_df * 10
第三行是标题
:
with open('AllData.csv', 'w') as handle:
udata_df.to_csv(handle, index=False)
pred_matrix.to_csv(handle, index=False)
f = 'AllData.csv'
df = pd.read_csv(f)
print (df)
iid rat uid
0 8 0 1
1 9 3 2
2 iid rat uid
3 80 0 10
4 90 30 20
参数header=False
之后它正常工作:
with open('AllData.csv', 'w') as handle:
udata_df.to_csv(handle, index=False)
pred_matrix.to_csv(handle, index=False, header=False)
f = 'AllData.csv'
df = pd.read_csv(f)
print (df)
iid rat uid
0 8 0 1
1 9 3 2
2 80 0 10
3 90 30 20
模式附加
解决方案:
f = 'AllData.csv'
udata_df.to_csv(f, index=False)
pred_matrix.to_csv(f,header=False, index=False, mode='a')
df = pd.read_csv(f)
print (df)
iid rat uid
0 8 0 1
1 9 3 2
2 80 0 10
3 90 30 20
concat
解决方案:
f = 'AllData.csv'
pd.concat([udata_df, pred_matrix]).to_csv(f, index=False)
df = pd.read_csv(f)
print (df)
iid rat uid
0 8 0 1
1 9 3 2
2 80 0 10
3 90 30 20
关于python - 使用 Pandas Python 将 Dataframe 的列从类型对象转换为 int/float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45607861/