python - 将 2 个数据帧与将 key 转换为 str 合并
问题描述
我有 2 个数据框
具有名为“文件名”的索引且类型为字符串的 df_features
df_features
Out[105]:
code 10012005 10029008 10197000 ... 9735005 9905009 9911007
filename ...
1 0.0 0.0 0.0 ... 0.0 0.0 0.0
10 0.0 0.0 0.0 ... 0.0 0.0 0.0
100 0.0 0.0 0.0 ... 0.0 0.0 0.0
10000 0.0 0.0 0.0 ... 0.0 0.0 0.0
10001 0.0 0.0 0.0 ... 0.0 0.0 0.0
... ... ... ... ... ... ...
9995 0.0 0.0 0.0 ... 0.0 0.0 0.0
9996 0.0 0.0 0.0 ... 0.0 0.0 0.0
9997 0.0 0.0 0.0 ... 0.0 0.0 0.0
9998 0.0 0.0 0.0 ... 0.0 0.0 0.0
9999 0.0 0.0 0.0 ... 0.0 0.0 0.0
[52713 rows x 4286 columns]
另一个数据框是 df_results,它有一个名为“文件名”的列,但类型是数字
df_results
Out[106]:
filename result
0 1.0 [NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, 280]
1 2.0 [NON, NON, NON, 288, NON, NON, NON, NON, NON, NON, NON, 285, 285, NON, NON, NON, NON, NON]
2 3.0 [NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, 285, NON]
3 4.0 [NON, NON, 287, NON, NON, 285, NON]
4 5.0 [NON, NON, NON, NON, NON]
... ...
52708 58593.0 [NON, NON, NON, NON, NON, NON, NON, NON, 285]
52709 58674.0 [NON, NON, NON, NON, NON, NON, NON]
52710 58788.0 [NON, NON, NON, NON, NON, NON]
52711 59173.0 [NON, NON, NON, NON, NON, NON, NON, NON, NON]
52712 59606.0 [NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, NON, 285, NON]
[52713 rows x 2 columns]
我想在“文件名”上将两个数据框合并为一个
所以我做了这个
df_results['filename'] = df_results['filename'].astype(str)
df = pd.merge(df_features, df_results, on = 'filename')
但是当我得到 df 它没有记录
所以我认为合并是错误的,因为 df_results 中的文件名转换为字符串
我的猜测是文件名变成了字符串,但带有小数点 .0
所以合并试图将“1234”与“1234.0”作为字符串匹配,但它们不匹配
我怎样才能解决这个问题?
解决方案
尝试转换到int
那时str
import pandas as pd
a = {'filename':[1.2,2.3,4.5]}
df = pd.DataFrame(a)
df.head(5)
filename
0 1.2
1 2.3
2 4.5
df["filename"] = df["filename"].fillna(0.0).astype(int).astype(str)
filename
0 1
1 2
2 4
推荐阅读
- python - 了解 Python 进程的内存增长(VmRSS 与 gc.get_objects)
- java - 使用 Java 读取图像文件的有效方法
- javascript - 单选按钮是或否调用 JavaScript 可见或隐藏选择列表
- python - QComboBox项及其值是其他文本框的功能,如何使用?
- javascript - 为什么 Firebase 命令不起作用?
- linux - MacOS 中的 Bash 脚本与 LInux 有何不同?
- php - Laravel 调用未定义的方法 App\\Model ::mapInto(), vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\ForwardsCalls.php
- c++ - MSVC 是否支持 C++11 样式的属性而不是 __declspec?
- python - for 关键字是否理解字符串是迭代?
- flutter - 如何在 post 方法中包含对象?HTTP