0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pandasのDataFrame 2つのリストからDataFrameを作ってファイル書き出しまで

Last updated at Posted at 2021-01-16

初めに

DataFrameって難しい。次の問題に頭を悩ませる。

  • list1とlist2をインデックス0とインデックス1に格納?
  • list1とlist2のインデックスが揃っているところでペア?

私の編み出した覚え方は、"知りたいのはアリス身長"。
これで「あ、アリスとアリスの身長をペアにすればいいんだ!」となる。

以下では2つの配列からDataFrame経由でファイル書き出しまで書き留める。

2つの1次元配列 → 2次元配列 → DataFrame → csvファイル

import pandas as pd

list1 = ['Alice', 'Bob', 'Charlie']
list2 = ['165', '175', '180']

dim2list = [[list1[i], list2[i]] for i in range(len(list1))]
df = pd.DataFrame(dim2list, columns=['Name', 'Length'])

df.to_csv('output.csv', index=False, header=True)

output.csv
Name,Length
Alice,165
Bob,175
Charlie,180

2つの1次元配列 → 2次元配列 → DataFrame → txtファイル

import pandas as pd

list1 = ['Alice', 'Bob', 'Charlie']
list2 = ['165', '175', '180']

dim2list = [[list1[i], list2[i]] for i in range(len(list1))]
df = pd.DataFrame(dim2list, columns=['Name', 'Length'])

df.to_csv('output.txt', sep='\t', index=False, header=True)
output.txt
Name	Length
Alice	165
Bob	175
Charlie	180

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?