嗨,我有一个问题将对象列表转换为整数列表。这些对象位于 Pandas 数据框“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:
改编了following post使用 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)
关于Python Pandas : convert list of objects to a list of integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55144642/