我正在尝试编写一个函数来比较两个DF,以便通过匹配lat和long来创建一个新的主DF,其中包含DF1中的“ id”和DF2中的“ _record_id”以及lat和long每一行。这是我正在使用的表的示例:
DF1 id Latitude Longitude
0 LA-DESI-A101 34.085778 -118.32779
1 LA-DESI-A102 34.086172 -118.327793
2 LA-DESI-A103 34.086511 -118.327791
3 LA-DESI-A104 34.0872 -118.327791
4 LA-DESI-A104 34.08707 -118.327594
DF2 id _latitude _longitude _record_id
0 LA-DESI-A001 34.086511 -118.327791 acbdefy-bbbb-cccc-b2c5-vvdasbhfgds
1 LA-DESI-B001 34.085778 -118.32779 acbdefy-bbbb-cccc-b2c5-voesadfegsd
2 LA-DESI-E004 34.086126 -118.324387 acbdefy-bbbb-cccc-b2c5-voplsadongg
3 LA-DESI-D005 34.086172 -118.327793 acbdefy-bbbb-cccc-b2c5-voasdkognoe
4 LA-DESI-D422 34.113367 -118.321414 acbdefy-bbbb-cccc-b2c5-voenposadkm
我仍在学习熊猫,经过一段时间的研究后,不确定如何做到这一点的最佳方法。我尝试使用np.where
,但不确定它的实际工作原理。.这是我所处位置的一个示例...
def compare():
cols = ['id', '_latitude', '_longitude', '_record_id']
MASTER = pd.DataFrame()
MasterDF = MASTER[cols]
MASTER['id'] =
MASTER['_latitude'].astype(float) = np.where((df1['Latitude'] == df2['_latitude']))
MASTER['_longitude'].astype(float) = np.where((df1['Longitude'] == df2['_longitude']))
MASTER['_record_id'] =
任何帮助或指导将不胜感激...
这是我的完整代码:
import os
import pandas as pd
import numpy as np
data = []
def scrapePPLX(directory, filename):
fname = open(directory, "r+")
lines = fname.readlines()
fname.close()
if '_' in filename:
polename = filename.split("_")[0]
else:
polename = filename.split(".")[0]
for line in lines:
if "<VALUE NAME=\"Latitude\" TYPE=\"Double\">" in line:
lat = line.split(">")[1].split("<")[0]
elif "<VALUE NAME=\"Longitude\" TYPE=\"Double\">" in line:
lon = line.split(">")[1].split("<")[0]
data.append([polename,lat, lon])
def main():
for subdir, dirs, files in os.walk(rootdir):
for file in files:
if file.endswith('.pplx'):
scrapePPLX(os.path.join(subdir,file), file)
cols=['id', 'Latitude','Longitude']
PPLXdf = pd.DataFrame(data)
PPLXdf.columns = cols
PPLXdf.to_csv('PPLXcsv.csv',index=False)
cols = ['id', '_latitude', '_longitude', '_record_id']
readCSV = pd.read_csv(pdc)
df = readCSV[cols]
df.to_csv('newPDC.csv', index=False)
compare(PPLXdf, df)
def compare(PPLXdf, df):
PPLXdf['Latitude'] = PPLXdf['Latitude'].astype(str)
PPLXdf['Longitude'] = PPLXdf['Longitude'].astype(str)
df['_latitude'] = df['_latitude'].astype(str)
df['_longitude'] = df['_longitude'].astype(str)
masterdf = PPLXdf.merge(df, left_on=['Latitude', 'Longitude'], right_on=['_latitude', '_longitude'])
masterdf.drop(['Latitude','Longitude'],axis=1,inplace=True)
masterdf.to_csv('Master.csv', index=False)
print("Enter the directory to recurse: ", end='', flush=True)
rootdir = input()
print("Enter name of the PDC: ", end='', flush=True)
pdc = rootdir + "\\" + input()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
参考Merge pandas DataFrame on column of float values,您可以尝试使用pd.merge(),但是在加入时需要小心,因为您具有浮点值。将浮点数转换为整数更安全。因此,您可以尝试执行以下操作:
df1['latint'] = np.round(df1['Latitude']*1000000).astype(int)
df1['longint'] = np.round(df1['Longitude']*1000000).astype(int)
df2['latint'] = np.round(df2['_latitude']*1000000).astype(int)
df2['longint'] = np.round(df2['_longitude']*1000000).astype(int)
dfmerged = pd.merge(df1, df2, how = 'inner', on = ['latint', 'longint'])
答案 1 :(得分:0)
这可以通过使用pandas.merge函数来实现。
它将生成输出,但由于列名不同,因此保留了两个数据框中的列。您将必须手动删除不必要的列。
例如
import pandas as pd
left = pd.DataFrame({'key1': ['A', 'B', 'C', 'D'], 'value':
np.random.randn(4)})
right = pd.DataFrame({'key2': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
在不同的数据框中有两个不同的列名“ key1”和“ key2”。
pd.merge(left, right, how='inner', left_on=['key1'], right_on=['key2'])
key1 value_x key2 value_y
0 B 0.410599 B 0.761038
1 D 1.454274 D 0.121675
Example2:如果要合并多个不同的列,则
pd.merge(left, right, how='inner', left_on=['key1','value1'], right_on=['key2','value2'])
在您的情况下,_latitude和_longitude的示例示例为
master_df = pd.merge(df1,d2,how='inner', left_on=['Latitude','Longitude'], right_on=['_latitude','_longitude'])
然后手动删除不必要的列
master_df.drop(['Latitude','Longitude'],axis=1,inplace=True)
答案 2 :(得分:0)
d1 = {'id': ['LA-DESI-A101','LA-DESI-A102','LA-DESI-A103', 'LA-DESI-A104','LA-DESI-A104'], 'Latitude': [34.085778, 34.086172, 34.086511, 34.0872, 34.08707], 'Longitude':[-118.32779, -118.327793, -118.327791, -118.327791, -118.327594]}
d2 = {'id': ['LA-DESI-A001', 'LA-DESI-B001', 'LA-DESI-E004', 'LA-DESI-D005', 'LA-DESI-D422'], '_latitude': [34.084511, 34.085778, 34.086126, 34.086172, 34.113367], '_longitude':[-118.327791, -118.32779, -118.324387, -118.327793, -188.321414], '_record_id': ['acbdefy-bbbb-cccc-b2c5-vvdasbhfgds','acbdefy-bbbb-cccc-b2c5-voesadfegsd', 'acbdefy-bbbb-cccc-b2c5-voplsadongg', 'acbdefy-bbbb-cccc-b2c5-voasdkognoe', 'acbdefy-bbbb-cccc-b2c5-voenposadkm']}
df1 = pd.DataFrame(data=d1)
df2 = pd.DataFrame(data=d2)
df1['Latitude'] = df1['Latitude'].astype(str)
df1['Longitude'] = df1['Longitude'].astype(str)
df2['_latitude'] = df2['_latitude'].astype(str)
df2['_longitude'] = df2['_longitude'].astype(str)
masterdf = df1.merge(df2, left_on=['Latitude', 'Longitude'], right_on=['_latitude', '_longitude'])