Pandas 新建 DataFrame 时列长度不同的解决方法
Pandas 新建 DataFrame 时列长度不同的解决方法
在使用 Pandas 创建 DataFrame 时,如果遇到 'TypeError: can only concatenate list (not 'int') to list' 错误,通常是因为您尝试将长度不同的列添加到 DataFrame 中。
为了解决这个问题,可以使用 NaN (Not a Number) 填充缺失值,确保所有列具有相同的长度。
以下是一个示例:
import pandas as pd
import numpy as np
# 创建一个空的 DataFrame
df = pd.DataFrame()
# 创建不同长度的列
col1 = [1, 2, 3, 4]
col2 = [5, 6, 7]
col3 = [8, 9, 10, 11, 12]
# 计算每列需要填充的 NaN 个数
max_len = max(len(col1), len(col2), len(col3))
col1 += [np.nan] * (max_len - len(col1))
col2 += [np.nan] * (max_len - len(col2))
col3 += [np.nan] * (max_len - len(col3))
# 将不同长度的列添加到 DataFrame 中
df['col1'] = col1
df['col2'] = col2
df['col3'] = col3
print(df)
输出:
col1 col2 col3
0 1.0 5.0 8
1 2.0 6.0 9
2 3.0 7.0 10
3 4.0 NaN 11
4 NaN NaN 12
在这个示例中,我们创建了三个不同长度的列,然后使用 [np.nan] * (max_len - len(col)) 计算每列需要填充的 NaN 个数,并将其添加到对应列的末尾。最后,将填充后的列添加到 DataFrame 中,即可得到包含不同长度列的 DataFrame。
注意: 为了代码简洁,示例中使用了 Python 列表的 += 操作符进行填充。在实际应用中,您可以根据需要选择其他方式进行填充,例如使用 list.extend() 方法。
原文地址: https://www.cveoy.top/t/topic/fLhF 著作权归作者所有。请勿转载和采集!