![](/img/trans.png)
[英]How to read a column without header from csv and save the output in a txt file using Python?
[英]How to keep the remove the second column from a .csv file and save the rest of the file to a .txt file in Python
我有一個包含兩列的.csv 文件, id
列包含 ids, score
列包含個人的分數,原始的.csv 文件如下所示:
import pandas as pd
record = pd.DataFrame({'id':['1234567891011', '1234567891012', '1234567891013'],
'score': [0.1, 0.2, 0.3]})
我想定義我的 function 以刪除score
列,然后以 id 不會變成 1.2345e+12 之類的格式保存id
列,結果應該類似於:
1234567891011
1234567891012
1234567891013
...
所以我嘗試使用以下代碼定義我的 function:
def get_id(fname):
'''Get id from fname and save it into .txt file'''
# read in fname as pandas.dataframe
df = pd.read_csv('fname', header = None, skiprows = 1)
# remove score column
df.drop(df.columns[1], axis = 1, inplace = True)
# transform the ids from int to str
df = df.astype(str)
# save df as .txt
df.to_csv('fname_txt', header = None, index = None, sep = '\n', mode = 'a')
return
當我測試上面的 function 時,它給了我一個 empty.txt 文件。 我知道我錯過了 function 中的某些內容,但我無法弄清楚我錯過了什么。 有更好的方法嗎? 另外,有沒有辦法可以將 .txt 文件的名稱保存為與 .csv 文件的名稱相同的名稱?
非常感謝!
您不使用fname
參數。 不應該是:
df = pd.read_csv(fname, header = None, skiprows = 1)
並保存這樣的東西:
df.to_csv(f"{fname}_txt.txt", header = None, index = None, sep = '\n', mode = 'a')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.