将向量分配给空的熊猫数据框

时间:2021-05-01 23:53:08

标签: python pandas dataframe

示例代码:

import numpy as np
import pandas as pd

df = pd.DataFrame()
arr = np.array(range(5))
vec = arr.reshape(-1,1)

# df['c0'] = vec # this line could not work
df['arr'] = arr # but we allow this one, just giving a default index
df['c1'] = vec # df has a index now, and this line works
df.index = range(0,10,2) # index changed
df['c2'] = vec # df changed index. but c1 and c2 are just the same.

print(df)

'c1' 和 'c2' 是一样的,这意味着赋值根本不关心索引到底是什么,只关心长度检查。

使 'c0' 无效有什么意义?如果我们只设置一个像 range(5) 这样的默认索引并允许这种分配会更好吗?

添加版本信息:

import sys
print(sys.version_info)
print('numpy: ' + np.__version__)
print('pandas: ' + pd.__version__)

sys.version_info(major=3, minor=9, micro=2, releaselevel='final', serial=0)

numpy: 1.20.1

熊猫:1.2.3

0 个答案:

没有答案