[英]How to group dataframe NaN values of one feature by another feature
[英]How to add feature values from one csv to another based on another feature rows
我建议您使用pandas
库。 如果您以前没有接触过它,那么它是一个使用非常广泛的数据操作库,可以让这项任务变得非常简单。 但是,它不是 Python 附带的标准库的一部分,因此根据您的环境,您可能需要使用 PyPi 安装它。 如果您以前没有这样做过,这样的指南可能会有所帮助。
在您的环境中安装 pandas 后,您可以运行以下代码(在您的文件路径中替换为csv1.csv
和csv2.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.