【问题标题】:Pandas to CSV inaccurate write tooPandas 到 CSV 的写入也不准确
【发布时间】:2021-09-17 21:24:11
【问题描述】:

下面是一个简单的 whois ip 搜索器,它接收一个名为 dupfree.csv 的 csv...

以上是我的示例文件。目前,当我运行以下脚本时,我完成了该过程,但数据框复制到 CSV 似乎正在复制所有行中项目 x 的响应。然后它添加一个新的 Row + Header 并为另一个 IP 添加数据。不知道我做错了什么,它清楚地处理了数据,只是索引与调用 IP 不匹配。

从调试中可以看出,我们在这两个项目上运行它。

def main ():
    df = pd.read_csv('dupfree.csv')
    temp = whoisyou(df)

        
def whoisyou(df):
    s = socket.socket()
    s.settimeout(10)
    for index,row in df.iterrows():
        DN = df.iloc[index]['ip']
        ipwhois = IPWhois(DN).lookup_rdap()
        df['network'] = ipwhois['asn_cidr']
        df['cidr'] = ipwhois['asn_description']
        df['country'] = ipwhois['asn_country_code']
        df['date'] = ipwhois['asn_date']
        DN = df.iloc[index]['ip']
        print (DN)
        print (df['date'])
        with open('csv_data.txt', 'w') as csv_file:
            df.to_csv('output.csv', header = True, mode='a')
            time.sleep (.5)

以下是从上述脚本运行收到的结果。如您所见,它反映了两个主机的数据,但它位于一个全新的标头中。

谢谢大家

【问题讨论】:

  • df.to_csv('output.csv', header = True, mode='a') 在你的循环中运行...

标签: python pandas dataframe csv


【解决方案1】:

您正在循环中使用header = True 写入CSV。使用header 的变量只写一次...例如

def whoisyou(df):
    s = socket.socket()
    s.settimeout(10)
    header = True
    for index,row in df.iterrows():
        DN = df.iloc[index]['ip']
        ipwhois = IPWhois(DN).lookup_rdap()
        df['network'] = ipwhois['asn_cidr']
        df['cidr'] = ipwhois['asn_description']
        df['country'] = ipwhois['asn_country_code']
        df['date'] = ipwhois['asn_date']
        DN = df.iloc[index]['ip']
        print (DN)
        print (df['date'])
        with open('csv_data.txt', 'w') as csv_file:
            df.to_csv('output.csv', header = header, mode='a')
            header = False
            time.sleep (.5)

可能有更好的方法来达到同样的效果,但上述方法应该可以。

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 2013-05-31
    • 1970-01-01
    相关资源
    最近更新 更多