簡體   English   中英

使用Python從Excel中提取列

[英]Extract columns from Excel using Python

我有一個帶有ff:row / col結構的Excel文件

ID   English   Spanish   French
 1   Hello     Hilo      Halu
 2   Hi        Hye       Ghi
 3   Bus       Buzz      Bas

我想閱讀Excel文件,提取行和列值,並根據英語,西班牙語和法語列創建3個新文件。

所以我會有類似的東西:

英文文件:

"1" = "Hello"
"2" = "Hi"
"3" = "Bus"

我一直在使用xlrd。 我可以打開,閱讀和打印文件的內容。 但是,這是我使用此命令(Excel文件已打開):

for index in xrange(0,2):
    theWord = '\n' + str(sh.col_values(index, start_rowx=index, end_rowx=1)) + '=' + str(sh.col_values(index+1, start_rowx=index, end_rowx = 1))
    print theWord

OUTPUT:

[u'Parameter/Variable/Key/String']=[u'ENGLISH'] <-- is this a list?, didn't the str() use to strip it out?

什么是ü做什么呢? 如何刪除方括號?

u意思是它是一個unicode字符串,當你調用str()時它被放在那里。 如果你將字符串寫入文件,它就不會存在。 你得到的是列中的一行。 這是因為你使用的是end_rowx=1它返回一個包含一個元素的列表。

嘗試獲取列值列表:

ids = sh.col_values(0, start_rowx=1)
english = sh.col_values(1, start_rowx=1)
spanish = sh.col_values(2, start_rowx=1)
french = sh.col_values(3, start_rowx=1)

然后你可以將它們zip成元組列表:

english_with_IDS = zip(ids, english)
spanish_with_IDS = zip(ids, spanish)
french_with_IDS = zip(ids, french)

其形式如下:

("1", "Hello"),("2", "Hi"), ("3", "Bus")

如果要打印對:

for id, word in english_with_IDS:
       print id + "=" + word

col_values返回列值列表,如果您想要單個值,可以調用sh.cell_value(rowx, cellx)

import xlrd

sh = xlrd.open_workbook('input.xls').sheet_by_index(0)
english = open("english.txt", 'w')
spanish = open("spanish.txt", 'w')
french = open("french.txt", 'w')
try:
    for rownum in range(sh.nrows):
        english.write(str(rownum)+ " = " +str(sh.cell(rownum, 0).value)+"\n")
        spanish.write(str(rownum)+ " = " +str(sh.cell(rownum, 1).value)+"\n")
        french.write(str(rownum)+ " = " +str(sh.cell(rownum, 2).value)+"\n")
finally:
    english.close()
    spanish.close()
    french.close()

使用熊貓

In [1]: import pandas as pd

In [2]: df = pd.ExcelFile('test.xls').parse('Sheet1', index_col=0) # reads file

In [3]: df.index = df.index.map(int)

In [4]: for col in df.columns:
   ...:     column = df[col]
   ...:     column.to_csv(column.name, sep='=')  # writes each column to a file                                                    
   ...:                                          # with filename == column name

In [5]: !cat English  # English file content
1=Hello
2=Hi
3=Bus

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM