我有以下索引DataFrame命名列和行不连续的数字:
a b c d
2 0.671399 0.101208 -0.181532 0.241273
3 0.446172 -0.243316 0.051767 1.577318
5 0.614758 0.075793 -0.451460 -0.012493
我想添加一个新列,'e',到现有的数据帧,并不想改变数据帧中的任何东西(即,新列始终具有与DataFrame相同的长度)。
0 -0.335485
1 -1.166658
2 -0.385571
dtype: float64
如何将列e添加到上面的例子中?
这是向pandas数据框架添加新列的特殊情况。在这里,我基于数据框架的现有列数据添加了一个新特性/列。
因此,让我们的dataFrame有列'feature_1', 'feature_2', 'probability_score',我们必须根据'probability_score'列中的数据添加一个new_column 'predicted_class'。
我将使用来自python的map()函数,并定义一个我自己的函数,该函数将实现如何给dataFrame中的每一行一个特定的class_label的逻辑。
data = pd.read_csv('data.csv')
def myFunction(x):
//implement your logic here
if so and so:
return a
return b
variable_1 = data['probability_score']
predicted_class = variable_1.map(myFunction)
data['predicted_class'] = predicted_class
// check dataFrame, new column is included based on an existing column data for each row
data.head()
import pandas as pd
# Define a dictionary containing data
data = {'a': [0,0,0.671399,0.446172,0,0.614758],
'b': [0,0,0.101208,-0.243316,0,0.075793],
'c': [0,0,-0.181532,0.051767,0,-0.451460],
'd': [0,0,0.241273,1.577318,0,-0.012493]}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
# Declare a list that is to be converted into a column
col_e = [-0.335485,-1.166658,-0.385571,0,0,0]
df['e'] = col_e
# add column 'e'
df['e'] = col_e
# Observe the result
df