将Numpy ndarray添加到datafram中

2024-04-20 05:44:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想向数据帧中的每一行添加一个numpy数组: 我确实有一个dataframe在每一行中保存一些数据,现在我想添加一个新的列,其中包含一个n元素数组。你知道吗

例如:

Name, Years
 Test, 2
 Test2, 4

现在我想补充一下:

testarray1 = [100, 101, 1 , 0, 0, 5] as a new column='array' to Name='Test'

Name, Years, array
 Test, 2, testarray1
 Test2, 4, NaN

我该怎么做?你知道吗


Tags: to数据nametestnumpy元素dataframenew
2条回答

试试这个

import pandas as pd
import numpy as np
df = pd.DataFrame({'name':['test', 'test2'], 'year':[1,2]})
print(df)

x = np.arange(5)
df['array']=[x,np.nan]
print(df)
import pandas as pd
import numpy as np

testarray1 = [100, 101, 1 , 0, 0, 5]

d = {'Name':['Test', 'Test2'], 
     'Years': [2, 4]
    }

df = pd.DataFrame(d)  # create a DataFrame of the data
df.set_index('Name', inplace=True)  # set the 'Name' column as the dataframe index

df['array'] = np.NaN  # create a new empty 'array' column (filled with NaNs)
df['array'] = df['array'].astype(object)  # convert it to an 'object' data type

df.at['Test', 'array'] = testarray1  # fill in the cell where index equals 'Test' and column equals 'array'

df.reset_index(inplace=True)  # if you don't want 'Name' to be the dataframe index

print(df)

    Name  Years                   array
0   Test      2  [100, 101, 1, 0, 0, 5]
1  Test2      4                     NaN

相关问题 更多 >