繁体   English   中英

如何根据另一个特征行将特征值从一个 csv 添加到另一个

[英]How to add feature values from one csv to another based on another feature rows

我有 2 个 csv 文件如下。 我必须根据 ID 将一个 csv 的 Lat 和 Long 功能添加到另一个

在此处输入图像描述

根据 ID,我必须将纬度和经度列添加到 CSV 1(ID 1 具有不同的值,ID 2 具有不同的值,依此类推。

谁能告诉我如何使用 python 执行此操作?

我建议您使用pandas库。 如果您以前没有接触过它,那么它是一个使用非常广泛的数据操作库,可以让这项任务变得非常简单。 但是,它不是 Python 附带的标准库的一部分,因此根据您的环境,您可能需要使用 PyPi 安装它。 如果您以前没有这样做过,这样的指南可能会有所帮助。

在您的环境中安装 pandas 后,您可以运行以下代码(在您的文件路径中替换为csv1.csvcsv2.csv )。

import pandas as pd

# Load the csv files into dataframes and set the index of each to the 'ID' column
df1 = pd.read_csv('csv1.csv').set_index('ID')
df2 = pd.read_csv('csv2.csv').set_index('ID')

# Join using how='outer' to keep all rows from both dataframes
joined = df1.join(df2, how='outer')
print(joined)

# Save to a new csv file
joined.to_csv('joined.csv')

我做了一些简单的示例数据来演示运行代码的结果:

csv1.csv:

ID,my_feature
1,banana
2,apple
3,pear

csv2.csv:

ID,latitude,longitude
1,7,-4
4,10,15

打印 output:

       my_feature  latitude  longitude
ID
1      banana       7.0       -4.0
2       apple       NaN        NaN
3        pear       NaN        NaN
4         NaN      10.0       15.0

Output加入。csv:

ID,my_feature,latitude,longitude
1,banana,7.0,-4.0
2,apple,,
3,pear,,
4,,10.0,15.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM