iT邦幫忙

0

Python資料合併

  • 分享至 

  • xImage

想請問各位大大,小弟想將一csv檔中的資料取出,裡面資料分為兩列,第一列為IP,第二列為port位,目前抓到的資料為一個列表中的值會以逗號分別隔開,但我想將兩列中的資料合併為123.123.123.123:8080類似這樣該如何做比較適合
目前的程式如下:

import csv
from csv import reader

with open('D:\Roger\work\ShodanRay.csv', 'r') as csvfile:
    csvfile = reader(csvfile)
    rows = [row for row in csvfile]

print(rows)

froce iT邦大師 1 級 ‧ 2023-03-09 12:48:08 檢舉
https://docs.python.org/zh-tw/3/library/csv.html

官網第一個範例就是你要的了。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
ccutmis
iT邦高手 2 級 ‧ 2023-03-09 13:58:23

假設 ShodanRay.csv 內容為:

192.168.0.1,192.168.31.1
8000,8080

程式範例:

import csv
with open('ShodanRay.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    ls = [row for row in spamreader]
print(ls)
new_ls = [ls[0][i]+':'+ls[1][i] for i in range(0,len(ls[0]))]
print(new_ls)

輸出結果:

[['192.168.0.1', '192.168.31.1'], ['8000', '8080']]
['192.168.0.1:8000', '192.168.31.1:8080']

補充 force 大大 加點的使用 zip 函式範例:

import csv
with open('ShodanRay.csv', newline='') as csvfile:
    ls = [ row for row in csv.reader(csvfile, delimiter=',') ]
    new_ls= list(map(lambda x:x[0]+':'+x[1],list(zip(ls[0],ls[1]))))
print(ls)
print(new_ls)

輸出結果:

[['192.168.0.1', '192.168.31.1'], ['8000', '8080']]
['192.168.0.1:8000', '192.168.31.1:8080']

補充一個不用任何模組的範例:

ls = [line.split(',') for line in open('ShodanRay.csv','r').readlines()]
new_ls= list(map(lambda x:(x[0]+':'+x[1]).replace('\n',''),list(zip(ls[0],ls[1]))))
print(ls)
print(new_ls)

輸出結果:

[['192.168.0.1', '192.168.31.1'], ['8000', '8080']]
['192.168.0.1:8000', '192.168.31.1:8080']
froce iT邦大師 1 級 ‧ 2023-03-09 14:51:41 檢舉

痾,他資料長這樣?
長這樣的話我會建議用zip處理。

ccutmis iT邦高手 2 級 ‧ 2023-03-09 15:09:50 檢舉

想說用簡單點的作法讓樓主看懂XD

0
mackuo
iT邦研究生 2 級 ‧ 2023-03-09 22:47:11
import pandas as pd

df = pd.read_csv('example.csv', header=None)
df

https://ithelp.ithome.com.tw/upload/images/20230309/201223354wuDFGTkLG.jpg

result = [(i + ":" + j) for i, j in zip(df.iloc[0], df.iloc[1])]

result

https://ithelp.ithome.com.tw/upload/images/20230309/20122335X3zKe5LBsv.jpg

我要發表回答

立即登入回答