[英]Python Pandas: convert list of objects to a list of integer
嗨,我有一個問題將對象列表轉換為整數列表 。 這些對象位於熊貓數據框“ Kanten”的“ stopsequence”列中。 在CSV導入和列中的數據清理之后,我收到了所有這些信息。 我正在使用Python 3.X
我是Python新手,也許這是問題的一部分。
import pandas as pd
import numpy as np
import os
import re
import ast
orgn_csv = pd.read_csv(r"Placeholder path for csv file")
df = orgn_csv.dropna()
Kanten = pd.DataFrame({"stopsequence" : df.stopsequence})
# In between is a block in which I use regular expressions for data cleaning purposes.
# I left the data cleaning block out to make the post shorter
Kanten.stopsequence = Kanten.stopsequence.str.split (',')
print (Kanten.head())
print (Kanten.stopsequence.dtype)
這給出以下輸出:
stopsequence
2 [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
3 [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
4 [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
5 [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
6 [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
object
我正在尋找一種方法來轉換包含對象的列表。 我仔細搜索了StackOverflow論壇,並嘗試了許多不同的方法。 沒有他們,我就成功了。 我嘗試使用:
Kanten.stopsequence = Kanten.stopsequence.astype(str).astype(int)
This Returns:
ValueError: invalid literal for int() with base 10:
使用atoi而不是atof修改了以下帖子
Kanten.stopsequence.applymap(atoi)
This Returns:
AttributeError: 'Series' object has no attribute 'applymap'
Kanten.stopsequence = list(map(int, Kanten.stopsequence))
This returns:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
Kanten.stopsequence = Kanten.stopsequence.apply(ast.literal_eval)
This returns:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
有人看到解決方案了嗎? 我不確定這是一個復雜的案例還是我缺乏進一步的編程經驗。 如果可能的話,簡短的解釋會有所幫助。 我自己也可以找到解決辦法。 先感謝您。
可以將pandas Series
輕松地轉換為列表,並且可以將列表列表作為創建DataFrame
輸入。
我認為這可以幫助:
splitted = pd.DataFrame(Kanten.stopsequence.str.split (','), index=Kanten.index).astype(int)
這將為您提供一個新的數據框,其索引與原始索引相同,但是每個元素都在其自己的列中。
如果相關,則可以合並該新列
pd.concat([Kanten, splitted], axis=1)
因此,從您第二次嘗試操作數據時,錯誤消息告訴您Kanten.stopsequence
是Series
,而不是DataFrame
。 要進行轉換,您需要訪問
list_of_lists = Kanten.stopsequence.to_numpy(dtype='int32').tolist()
請注意,這將為您的數據創建一個嵌套的2d數據數組。 要訪問第一行中的第一個整數,您需要編寫list_of_lists[0][0]
。
這就是我將DataFrame的最后一列拉入一個int列表的方法。
假設.csv
與.py
腳本位於同一目錄中,稱為kanten.csv
。 您要查找的列是stopsequence
。
import os
import pandas as pd
path=os.getcwd()
filename = 'kanten.csv'
filepath = os.path.join(path, filename)
kanten = pd.read_csv(filepath)
list = list(kanten['stopsequence'].apply(lambda x: int(x)))
在最后一行中,從stopsequence
中提取了stopsequence
列,將值kanten
轉換為整數,然后將該列轉換為標准的python列表對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.