Python将多个数组值写入csv

时间:2017-10-11 09:02:01

标签: python

使用我的代码,我读取了JSON数据的值并插入到数组

def retrive_json():
    with open('t_v1.json') as json_data:
        d = json.load(json_data)
    array = []
    for i in d['ride']:
        origin_lat = i['origin']['lat']
        origin_lng = i['origin']['lng']
        destination_lat = i['destination']['lat']
        destination_lng = i['destination']['lng']
        array.append([origin_lat,origin_lng,destination_lat,destination_lng])

    return array

结果数组是:

[[39.72417, -104.99984, 39.77446, -104.9379], [39.77481, -104.93618, 39.6984, -104.9652]]

如何将每个数组的每个元素写入csv中的特定字段? 我试过这样的方式:

wrt = csv.writer(open(t_.csv', 'w'), delimiter=',',lineterminator='\n')
for x in jjson:
    wrt.writerow([x])

但每个数组的值都存储在一个字段中 如何解决它并在一个字段中写每个?

这是我的json文件:

{
"ride":[
  {
     "origin":{
        "lat":39.72417,
        "lng":-104.99984,
        "eta_seconds":null,
        "address":""
     },
     "destination":{
        "lat":39.77446,
        "lng":-104.9379,
        "eta_seconds":null,
        "address":null
     }
  },
  {
     "origin":{
        "lat":39.77481,
        "lng":-104.93618,
        "eta_seconds":null,
        "address":"10 Albion Street"
     },
     "destination":{
        "lat":39.6984,
        "lng":-104.9652,
        "eta_seconds":null,
        "address":null
     }
  }
]
}

4 个答案:

答案 0 :(得分:1)

这可能会有所帮助:

import json
import csv

def retrive_json():
    with open('data.json') as json_data:
        d = json.load(json_data)
    array = []
    for i in d['ride']:
        origin_lat = i['origin']['lat']
        origin_lng = i['origin']['lng']
        destination_lat = i['destination']['lat']
        destination_lng = i['destination']['lng']
        array.append([origin_lat,origin_lng,destination_lat,destination_lng])

    return array



res = retrive_json()

csv_cols = ["orgin_lat", "origin_lng", "dest_lat", "dest_lng"]

with open("output_csv.csv", 'w') as out:
    writer = csv.DictWriter(out, fieldnames=csv_cols)

    writer.writeheader()
    for each_list in res:
        d = dict(zip(csv_cols,each_list))
        writer.writerow(d)

生成的输出csv是:

orgin_lat,origin_lng,dest_lat,dest_lng
39.72417,-104.99984,39.77446,-104.9379
39.77481,-104.93618,39.6984,-104.9652

答案 1 :(得分:1)

我们说我们有这个:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Main {

    public static JFrame f = new JFrame();
    // Pointless, applets are deprecated
    // Besides, this isn't how you use them
    //public static JApplet a = new JApplet();
    public static JPanel p = new JPanel();
    public static JButton b = new JButton();
    public static JScrollPane pane = new JScrollPane(p, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    public static JLabel gameimage;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                f.setSize(1000, 800);

                //a.setBounds(0, 0, 1000, 800);
                //a.setVisible(true);
                //a.setBackground(Color.WHITE);
                // Pointless, the layout manager of the JScrollPane
                // will make these choices
                //p.setBounds(0, 0, 1000, 800);
                p.setVisible(true);
                p.setBackground(Color.WHITE);
                // !! This is root of your problem !!
                //p.setLayout(null);
                p.setLayout(new BorderLayout());
                // Pointless, it already is
                //p.setOpaque(true);

                // Pointless, you don't do anything with the returned value
                //pane.getVerticalScrollBar();
                //pane.getHorizontalScrollBar();
                // Pointless, it already is
                //pane.setVisible(true);
                // Pointless
                //b.setBounds(955, 0, 40, 30);
                b.setText("+");
                b.setFont(new Font("Times Roman", Font.BOLD, 30));
                // Pointless
                //b.setVisible(true);
                b.setBorder(javax.swing.BorderFactory.createLineBorder(Color.WHITE));
                b.setBackground(Color.WHITE);
                b.setForeground(Color.GREEN);

                b.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        JFileChooser file = new JFileChooser();

                        file.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                        file.setAcceptAllFileFilterUsed(true);

                        if (file.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                            int width;
                            int height;
                            File f = file.getSelectedFile();
                            try {
                                BufferedImage bimg = ImageIO.read(new File(f.getAbsolutePath()));
                                width = bimg.getWidth();
                                height = bimg.getHeight();
                                String fname = f.getAbsolutePath();
                                if (gameimage != null) {
                                    p.remove(gameimage);
                                }
                                gameimage = new JLabel("", new ImageIcon(fname), JLabel.CENTER);
                                gameimage.setSize(width, height);
                                gameimage.setOpaque(true);

                                //a.revalidate();
                                //a.repaint();
                                //p.removeAll();
                                // Not really what you want to do right now
                                // Besides, if you use a null layout, it won't do anything
                                //p.revalidate();
                                //p.repaint();
                                //pane.revalidate();
                                //pane.repaint();
                                //p.setSize(width, height);
                                p.add(gameimage);
                                //p.add(b);
                                //p.add(pane);
                                // Presumaly, pane should alredy be added to a container
                                //a.getContentPane().add(pane);
                                p.revalidate();
                                p.repaint();
                            } catch (IOException ioe) {

                            }

                        } else {
                            System.out.println("not working");
                        }
                    }
                });

                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                // Not what you want to call here
                //f.setVisible(true);
                // Probably not the best idea right now
                f.setResizable(false);
                //f.add(a);
                //a.add(p);
                // Good idea to add the scollpane to the container
                f.add(pane);
                p.add(b, BorderLayout.SOUTH);
                f.setVisible(true);
            }
        });
    }
}

这是一个熊猫解决方案:

jsonstring = """{
    "ride":[
      {
         "origin":{
            "lat":39.72417,
            "lng":-104.99984,
            "eta_seconds":null,
            "address":""
         },
         "destination":{
            "lat":39.77446,
            "lng":-104.9379,
            "eta_seconds":null,
            "address":null
         }
      },
      {
         "origin":{
            "lat":39.77481,
            "lng":-104.93618,
            "eta_seconds":null,
            "address":"10 Albion Street"
         },
         "destination":{
            "lat":39.6984,
            "lng":-104.9652,
            "eta_seconds":null,
            "address":null
         }
      }
    ]
    }"""

返回:

import pandas as pd
import json

# Load json to dataframe
df = pd.DataFrame(json.loads(jsonstring)["ride"])
# Create the new columns
df["o1"] = df["origin"].apply(lambda x: x["lat"])
df["o2"] = df["origin"].apply(lambda x: x["lng"])
df["d1"] = df["destination"].apply(lambda x: x["lat"])
df["d2"] = df["destination"].apply(lambda x: x["lng"])

#export
print(df.iloc[:,2:].to_csv(index=False, header=True))
#use below for file
#df.iloc[:,2:].to_csv("output.csv", index=False, header=True) 

简明回答:

o1,o2,d1,d2
39.72417,-104.99984,39.77446,-104.9379
39.77481,-104.93618,39.6984,-104.9652

或者,也许是最易读的解决方案:

import pandas as pd
import json
with open('data.json') as json_data:
    d = json.load(json_data)
df = pd.DataFrame(d["ride"])
df["o1"],df["o2"] = zip(*df["origin"].apply(lambda x: (x["lat"],x["lng"])))
df["d1"],df["d2"] = zip(*df["destination"].apply(lambda x: (x["lat"],x["lng"])))
df.iloc[:,2:].to_csv("t_.csv",index=False,header=False)

答案 2 :(得分:0)

对我来说,看起来你有一个阵列数组,你想要各个元素。因此,您需要使用嵌套的for循环。你当前的for循环正在获取每个数组,然后将每个数组拆分成你想要循环遍历它们的元素。我建议这样的事情:

for x in jjson:
    for y in x:
        wrt.writerow([y])

显然你可能想要更新你的包围等等,这只是让你知道如何解决你的问题。

让我知道它是怎么回事!

答案 3 :(得分:0)

为什么csv - 图书馆?

array = [[1, 2, 3, 4], [5, 6, 7, 8]]

with open('test.csv', 'w') as csv_file :
    csv_file.write("# Header Info\n" \
                   "# Value1, Value2, Value3, Value4\n")   # The header might be optional

    for row in array :
         csv_file.write(",".join(row) + "\n")