python - 将 pd.dataframe 中的部分列替换为具有不同长度的数组

标签 python pandas dataframe

我想创建一个包含多个长度不同的列的数据框,因为我认为这对于 pd.dataframe 是不可能的我之前存储过(不同长度)。我已经尝试过 dataframe.replace 和 dataframe.update 但我无法得到这个结果。

enter image description here

数组的类型和形状是: enter image description here

最佳答案

您必须从索引 1 插入数组。为此你可以做到,

df['dobs'][1:] = dobs

所有数组都类似。

考虑一个示例数据框,

df = pd.DataFrame()

df['dobs'] = [0.] * 45
df['dpred_0'] = [0.] * 45
df['dpred'] = [0.] * 45
df['mrec'] = [0.] * 45

现在,一些你在问题中提到的形状的占位符数组,

dobs = np.array([x for x in range(1, 45)])
dpred_0 = np.array([x for x in range(1, 45)])
dpred = np.array([x for x in range(1, 45)])
mrec = np.array([x for x in range(1, 46)])

让我们检查形状,

print(dobs.shape, dpred_0.shape, dpred.shape, mrec.shape, df.shape) # ((44,), (44,), (44,), (45,), (45, 4))

要将索引 1 中的列替换为更短的数组,您可以这样做,

df['dobs'][1:] = dobs
df['dpred_0'][1:] = dpred_0
df['dpred'][1:] = dpred
df['mrec'] = mrec # mrec is of shape (45, ) so no need to start from index 1

   dobs    dpred_0  dpred   mrec
0   0.0      0.0    0.0      1
1   1.0      1.0    1.0      2
2   2.0      2.0    2.0      3
3   3.0      3.0    3.0      4
4   4.0      4.0    4.0      5

关于python - 将 pd.dataframe 中的部分列替换为具有不同长度的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55761175/

相关文章:

python - 从 pandas 的数据框列中搜索字符串模式

python - 如何用pivot reshape pandas数据框?

python - 按数据框列中的标签数组过滤和分组

python-3.x - 如何在多列中使用 pd.melt()?

python - 如何在 Python 中计算字符串的数字、字母、空格?

python - Django 三元关系

python - 如何使用 haversine 距离矩阵返回满足距离阈值标准的所有点对

python - DeepFace verify() 可以接受图像数组或 PIL Image 对象吗?

python - 使用python如何计算四分位数/百分位数并给出创建新列进行分析的标准?

r - Dplyr 使用字符串变量作为表达式重命名