我有一个矩阵,其中一列是 CSV,如下所示:-
matrix = [
[1,"123,354,23"],
[2,"234,34,678"]
]
如何标准化这一点,以便我为 CSV 列中的每个值获取一行,即,使其看起来像这样:-
[
[1, 123],
[1, 354],
[1, 23],
[2, 234],
[2, 34],
[2, 678]
]
我愿意使用 numpy 或 pandas。
请注意,在我的具体情况下,还有许多其他非 CSV 列。
谢谢
最佳答案
在您给出的示例中,这将完成:
matrix = [
[1,"123,354,23"],
[2,"234,34,678"]
]
import ast
expanded = [
[ index, item ]
for index, rowString in matrix
for item in ast.literal_eval('[' + rowString + ']')
]
对于其他“非 CSV”案例,这取决于它们的格式。在这里,ast.literal_eval 是一个很好的工具,用于将明显的标准(逗号分隔的字符串)转换为变量 item
可以迭代的 Python 序列。其他格式可能需要其他转换方法。
这会生成与您指定的完全相同的列表列表。不过,pandas
是一个很好的工具。然后,要将列表列表转换为 pandas.DataFrame
,您可以说:
import pandas as pd
df = pd.DataFrame(expanded, columns=['index', 'item']).set_index(['index'])
print(df)
# prints:
#
# item
# index
# 1 123
# 1 354
# 1 23
# 2 234
# 2 34
# 2 678
或者,如果“许多其他非 CSV 列”只是指矩阵每一行中任意数量的附加条目,但最后一个条目仍然始终是 CSV 文本,那么它可能如下所示:
matrix = [
[1, 3.1415927, 'Mary Poppins', "123,354,23"],
[2, 2.7182818, 'Genghis Khan', "234,34,678"]
]
import ast
expanded = [
row[:-1] + [item]
for row in matrix
for item in ast.literal_eval('[' + row[-1] + ']')
]
import pandas as pd
df = pd.DataFrame(expanded).set_index([0])
关于python - 如何使用一个 CSV 列标准化 Python 矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58998361/