[英]Reading comma-separated words into pandas
我有一個像這樣的文件:
words.txt
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O"
如何使用Pandas讀取此文件? 我的最終目標將是一個包含(A,B,C,D,E..O)的系列
read_csv似乎適合表。
我設法做到這一點
words = list(pd.read_csv('words.txt').columns)
但這太丑了。 我敢肯定有更好的方法。
謝謝!
這是一個答案
list = ["A", "B", "C", "D", "E","F", "G", "H", "I", "J","K", "L", "M", "N", "O"]
print(list)
輸出:
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
使用純python,您可以執行以下操作來建立列表:
words = [word.strip() for line in open("words.txt") for word in line.split(",") if word]
您不需要單獨的pandas庫,只需使用csv
模塊即可。 范例-
import csv
with open('<csvfile>','r') as f:
reader = csv.reader(f,skipinitialspace=True)
words = next(reader)
skipinitialspace
是跳過定界符之后的空白,它似乎在您的csv中。
示例/演示-
我的a.csv
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"
代碼和結果-
>>> import csv
>>> with open('a.csv','r') as f:
... reader = csv.reader(f,skipinitialspace=True)
... words = next(reader)
...
>>> words
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.