【问题标题】:writing out after comparing columns from 2 csv/dataframes比较来自 2 个 csv/数据帧的列后写出
【发布时间】:2016-05-04 14:20:23
【问题描述】:

我觉得有一种非常直观的方法可以使用 for 循环来做到这一点,但我目前被卡住了。我得到了它的一部分,但用伪代码填充了其余部分。非常感谢您对此的帮助。

import pandas as pd
first_df= pd.read_csv('city_states.csv')

second_df = pd.read_csv('locations.csv);

for i in first_df[:,0]: #city column
for j in first_df[:,1] #state column

伪代码

if i == second_df[:1]: # state column in second data frame
    and if j == second_df[:2]: # city column in second data frame

如果与制表符分隔的文本文件匹配,则写入经度和纬度

这就是我想要做的目前我正在尝试从一个 csv 生成经度和纬度,如果它包含在另一个 csv 中。也许是数据框。我正在寻找最佳选择

location.csv

zip state   city    lat lng
35004   AL  Acmar   33.584132   -86.51557
35005   AL  Adamsville  33.588437   -86.959727
35006   AL  Adger   33.434277   -87.167455
35007   AL  Keystone    33.236868   -86.812861
35010   AL  New Site    32.941445   -85.951086
5014    AL  Alpine  33.331165   -86.208934
35016   AL  Arab    34.328339   -86.489638

如果城市和州与第二个 csv 的城市和州匹配。我们需要创建一个 txt 文件,其中长和纬度由制表符分隔,如上面的伪代码中所写。第一个数据框是指city_state.csv,第二个数据框是指locations.csv,其中包含我们尝试提取的经纬度(如果有匹配)

city_state.csv

City        State
Burlington  VT
Minneapolis  MN
Bloomington  IN
Irvine  CA

预期输出

 95.64652295    36.70384646 
 72.6535921  23.0519796  
-86.2651028 43.222406   
 55.29835975 25.25033149 
-117.87059452   34.11669299 
-80.26491717    25.80180169 

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为你需要mergeto_csv

    print df1
         zip state        city        lat        lng
    0  35004    AL       Acmar  33.584132 -86.515570
    1  35005    AL  Adamsville  33.588437 -86.959727
    2  35006    AL       Adger  33.434277 -87.167455
    3  35007    AL    Keystone  33.236868 -86.812861
    4  35010    AL     NewSite  32.941445 -85.951086
    5   5014    AL      Alpine  33.331165 -86.208934
    6  35016    AL        Arab  34.328339 -86.489638
    
    print df2
              City State
    0       Alpine    AL
    1  Minneapolis    MN
    2  Bloomington    IN
    3       Irvine    CA
    
    df = pd.merge(df1, df2, left_on=['state','city'], right_on=['State','City'])
    print df
        zip state    city        lat        lng    City State
    0  5014    AL  Alpine  33.331165 -86.208934  Alpine    AL
    
    df[['lat','lng']].to_csv('filename.txt', sep='\t', header=False, index=False)
    

    【讨论】:

    • 请检查我的解决方案。对我来说有点不清楚write the longitude and latitude if a match occures to text file delimted by tab。您是否需要只写列lanlong?您可以添加所需的输出吗?也许你可以很少改变输入,因为在你的没有匹配。
    • 哇太棒了,但我只是在寻找 lan,很想写入文本文件
    • 确定刚刚添加了期望输出
    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多