簡體   English   中英

如何向現有的 DataFrame 添加新列?

[英]How to add a new column to an existing DataFrame?

我有以下索引 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列添加到上面的示例中?

編輯 2017

正如評論和@Alexander 所指出的,目前將 Series 的值添​​加為 DataFrame 的新列的最佳方法可能是使用assign

df1 = df1.assign(e=pd.Series(np.random.randn(sLength)).values)

編輯 2015
有些人報告說使用此代碼獲得了SettingWithCopyWarning
但是,該代碼仍然可以在當前的 pandas 0.16.1 版本中完美運行。

>>> sLength = len(df1['a'])
>>> df1
          a         b         c         d
6 -0.269221 -0.026476  0.997517  1.294385
8  0.917438  0.847941  0.034235 -0.448948

>>> df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)
>>> df1
          a         b         c         d         e
6 -0.269221 -0.026476  0.997517  1.294385  1.757167
8  0.917438  0.847941  0.034235 -0.448948  2.228131

>>> pd.version.short_version
'0.16.1'

SettingWithCopyWarning旨在通知數據幀副本上可能無效的分配。 它不一定說你做錯了(它可能會觸發誤報),但從 0.13.0 開始,它讓你知道有更合適的方法用於相同的目的。 然后,如果您收到警告,請遵循其建議:嘗試使用 .loc[row_index,col_indexer] = value 代替

>>> df1.loc[:,'f'] = pd.Series(np.random.randn(sLength), index=df1.index)
>>> df1
          a         b         c         d         e         f
6 -0.269221 -0.026476  0.997517  1.294385  1.757167 -0.050927
8  0.917438  0.847941  0.034235 -0.448948  2.228131  0.006109
>>> 

事實上,這是目前熊貓文檔中描述的更有效的方法


原答案:

使用原始 df1 索引創建系列:

df1['e'] = pd.Series(np.random.randn(sLength), index=df1.index)

這是添加新列的簡單方法: df['e'] = e

我想在現有數據框中添加一個新列“e”,並且不要更改數據框中的任何內容。 (該系列的長度始終與數據框相同。)

我假設e中的索引值與df1中的索引值匹配。

啟動名為e的新列的最簡單方法,並為其分配系列e中的值:

df['e'] = e.values

分配(熊貓 0.16.0+)

從 Pandas 0.16.0 開始,您還可以使用assign ,它將新列分配給 DataFrame 並返回一個新對象(副本),其中包含除新列之外的所有原始列。

df1 = df1.assign(e=e.values)

根據此示例(其中還包括assign函數的源代碼),您還可以包含多個列:

df = pd.DataFrame({'a': [1, 2], 'b': [3, 4]})
>>> df.assign(mean_a=df.a.mean(), mean_b=df.b.mean())
   a  b  mean_a  mean_b
0  1  3     1.5     3.5
1  2  4     1.5     3.5

在您的示例中:

np.random.seed(0)
df1 = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = len(df1['a'])
e = pd.Series(np.random.randn(sLength))

>>> df1
          a         b         c         d
0  1.764052  0.400157  0.978738  2.240893
2 -0.103219  0.410599  0.144044  1.454274
3  0.761038  0.121675  0.443863  0.333674
7  1.532779  1.469359  0.154947  0.378163
9  1.230291  1.202380 -0.387327 -0.302303

>>> e
0   -1.048553
1   -1.420018
2   -1.706270
3    1.950775
4   -0.509652
dtype: float64

df1 = df1.assign(e=e.values)

>>> df1
          a         b         c         d         e
0  1.764052  0.400157  0.978738  2.240893 -1.048553
2 -0.103219  0.410599  0.144044  1.454274 -1.420018
3  0.761038  0.121675  0.443863  0.333674 -1.706270
7  1.532779  1.469359  0.154947  0.378163  1.950775
9  1.230291  1.202380 -0.387327 -0.302303 -0.509652

可在此處找到首次引入此新功能時的說明。

超級簡單的列分配

pandas 數據框被實現為列的有序字典。

這意味着__getitem__ []不僅可以用來獲取某個列,而且__setitem__ [] =可以用來分配一個新列。

例如,這個數據框可以通過簡單地使用[]訪問器來添加一個列

    size      name color
0    big      rose   red
1  small    violet  blue
2  small     tulip   red
3  small  harebell  blue

df['protected'] = ['no', 'no', 'no', 'yes']

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes

請注意,即使數據幀的索引關閉,這也有效。

df.index = [3,2,1,0]
df['protected'] = ['no', 'no', 'no', 'yes']
    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes

[]= 是要走的路,但要小心!

但是,如果您有一個pd.Series並嘗試將其分配給索引關閉的數據框,您將遇到麻煩。 參見示例:

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'])
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no

這是因為默認情況下pd.Series具有從 0 到 n 枚舉的索引。 pandas [] =方法試圖變得“聰明”

究竟發生了什么。

當您使用[] =方法時,pandas 正在使用左側數據幀的索引和右側系列的索引悄悄地執行外部連接或外部合並。 df['column'] = series

邊注

這很快就會導致認知失調,因為[]=方法試圖根據輸入做很多不同的事情,除非你只知道pandas 是如何工作的,否則無法預測結果。 因此,我建議不要在代碼庫中使用[]= ,但是在筆記本中探索數據時,這很好。

繞過問題

如果您有一個pd.Series並希望它從上到下分配,或者如果您正在編寫生產代碼並且您不確定索引順序,那么為此類問題進行保護是值得的。

您可以將pd.Series向下轉換為np.ndarraylist ,這樣就可以了。

df['protected'] = pd.Series(['no', 'no', 'no', 'yes']).values

或者

df['protected'] = list(pd.Series(['no', 'no', 'no', 'yes']))

但這不是很明確。

一些編碼員可能會說“嘿,這看起來多余,我會優化它”。

顯式方式

pd.Series的索引設置為df的索引是明確的。

df['protected'] = pd.Series(['no', 'no', 'no', 'yes'], index=df.index)

或者更現實地說,您可能已經有一個pd.Series可用。

protected_series = pd.Series(['no', 'no', 'no', 'yes'])
protected_series.index = df.index

3     no
2     no
1     no
0    yes

現在可以分配

df['protected'] = protected_series

    size      name color protected
3    big      rose   red        no
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue       yes

df.reset_index()的替代方法

由於索引不協調是問題所在,如果您覺得數據幀的索引不應該決定事情,您可以簡單地刪除索引,這應該更快,但它不是很干凈,因為您的函數現在可能做兩件事。

df.reset_index(drop=True)
protected_series.reset_index(drop=True)
df['protected'] = protected_series

    size      name color protected
0    big      rose   red        no
1  small    violet  blue        no
2  small     tulip   red        no
3  small  harebell  blue       yes

關於df.assign的注意事項

雖然df.assign更明確地說明了你在做什么,但它實際上存在與上述[]=相同的問題

df.assign(protected=pd.Series(['no', 'no', 'no', 'yes']))
    size      name color protected
3    big      rose   red       yes
2  small    violet  blue        no
1  small     tulip   red        no
0  small  harebell  blue        no

請注意df.assign您的列不稱為self 它會導致錯誤。 這使得df.assign異味,因為函數中有這類偽影。

df.assign(self=pd.Series(['no', 'no', 'no', 'yes'])
TypeError: assign() got multiple values for keyword argument 'self'

你可能會說,“好吧,那我就不用self了”。 但是誰知道這個函數將來會如何改變以支持新的論點。 也許您的列名將成為熊貓新更新中的參數,從而導致升級問題。

似乎在最近的 Pandas 版本中,要走的路是使用df.assign

df1 = df1.assign(e=np.random.randn(sLength))

它不會產生SettingWithCopyWarning

直接通過NumPy執行此操作將是最有效的:

df1['e'] = np.random.randn(sLength)

請注意,我最初的(非常舊的)建議是使用map (速度要慢得多):

df1['e'] = df1['a'].map(lambda x: np.random.random())

最簡單的方法:-

data['new_col'] = list_of_values

data.loc[ : , 'new_col'] = list_of_values

這樣,您可以在 pandas 對象中設置新值時避免所謂的鏈式索引。 點擊這里進一步閱讀

如果要將整個新列設置為初始基值(例如None ),可以這樣做: df1['e'] = None

這實際上會將“對象”類型分配給單元格。 因此,稍后您可以自由地將復雜的數據類型(如列表)放入單個單元格中。

我得到了可怕的SettingWithCopyWarning ,並沒有通過使用 iloc 語法來解決。 我的 DataFrame 是由 read_sql 從 ODBC 源創建的。 使用上面lowtech的建議,以下內容對我有用:

df.insert(len(df.columns), 'e', pd.Series(np.random.randn(sLength),  index=df.index))

這可以很好地在最后插入列。 我不知道它是否是最有效的,但我不喜歡警告信息。 我認為有更好的解決方案,但我找不到,我認為這取決於索引的某些方面。
注意 這只能工作一次,如果嘗試覆蓋現有列,則會給出錯誤消息。
注意如上所述,從 0.16.0 開始分配是最好的解決方案。 請參閱文檔http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html#pandas.DataFrame.assign適用於不覆蓋中間值的數據流類型。

  1. 首先創建一個具有相關數據的python list_of_e
  2. 使用這個: df['e'] = list_of_e

創建一個空列

df['i'] = None

如果您嘗試添加的列是系列變量,則只需:

df["new_columns_name"]=series_variable_name #this will do it for you

即使您要替換現有列,這也很有效。只需鍵入與要替換的列相同的 new_columns_name。它只會用新的系列數據覆蓋現有列數據。

如果數據框和 Series 對象具有相同的 indexpandas.concat也可以在這里工作:

import pandas as pd
df
#          a            b           c           d
#0  0.671399     0.101208   -0.181532    0.241273
#1  0.446172    -0.243316    0.051767    1.577318
#2  0.614758     0.075793   -0.451460   -0.012493

e = pd.Series([-0.335485, -1.166658, -0.385571])    
e
#0   -0.335485
#1   -1.166658
#2   -0.385571
#dtype: float64

# here we need to give the series object a name which converts to the new  column name 
# in the result
df = pd.concat([df, e.rename("e")], axis=1)
df

#          a            b           c           d           e
#0  0.671399     0.101208   -0.181532    0.241273   -0.335485
#1  0.446172    -0.243316    0.051767    1.577318   -1.166658
#2  0.614758     0.075793   -0.451460   -0.012493   -0.385571

如果它們沒有相同的索引:

e.index = df.index
df = pd.concat([df, e.rename("e")], axis=1)

萬無一失:

df.loc[:, 'NewCol'] = 'New_Val'

例子:

df = pd.DataFrame(data=np.random.randn(20, 4), columns=['A', 'B', 'C', 'D'])

df

           A         B         C         D
0  -0.761269  0.477348  1.170614  0.752714
1   1.217250 -0.930860 -0.769324 -0.408642
2  -0.619679 -1.227659 -0.259135  1.700294
3  -0.147354  0.778707  0.479145  2.284143
4  -0.529529  0.000571  0.913779  1.395894
5   2.592400  0.637253  1.441096 -0.631468
6   0.757178  0.240012 -0.553820  1.177202
7  -0.986128 -1.313843  0.788589 -0.707836
8   0.606985 -2.232903 -1.358107 -2.855494
9  -0.692013  0.671866  1.179466 -1.180351
10 -1.093707 -0.530600  0.182926 -1.296494
11 -0.143273 -0.503199 -1.328728  0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832  0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15  0.955298 -1.430019  1.434071 -0.088215
16 -0.227946  0.047462  0.373573 -0.111675
17  1.627912  0.043611  1.743403 -0.012714
18  0.693458  0.144327  0.329500 -0.655045
19  0.104425  0.037412  0.450598 -0.923387


df.drop([3, 5, 8, 10, 18], inplace=True)

df

           A         B         C         D
0  -0.761269  0.477348  1.170614  0.752714
1   1.217250 -0.930860 -0.769324 -0.408642
2  -0.619679 -1.227659 -0.259135  1.700294
4  -0.529529  0.000571  0.913779  1.395894
6   0.757178  0.240012 -0.553820  1.177202
7  -0.986128 -1.313843  0.788589 -0.707836
9  -0.692013  0.671866  1.179466 -1.180351
11 -0.143273 -0.503199 -1.328728  0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832  0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15  0.955298 -1.430019  1.434071 -0.088215
16 -0.227946  0.047462  0.373573 -0.111675
17  1.627912  0.043611  1.743403 -0.012714
19  0.104425  0.037412  0.450598 -0.923387

df.loc[:, 'NewCol'] = 0

df
           A         B         C         D  NewCol
0  -0.761269  0.477348  1.170614  0.752714       0
1   1.217250 -0.930860 -0.769324 -0.408642       0
2  -0.619679 -1.227659 -0.259135  1.700294       0
4  -0.529529  0.000571  0.913779  1.395894       0
6   0.757178  0.240012 -0.553820  1.177202       0
7  -0.986128 -1.313843  0.788589 -0.707836       0
9  -0.692013  0.671866  1.179466 -1.180351       0
11 -0.143273 -0.503199 -1.328728  0.610552       0
12 -0.923110 -1.365890 -1.366202 -1.185999       0
13 -2.026832  0.273593 -0.440426 -0.627423       0
14 -0.054503 -0.788866 -0.228088 -0.404783       0
15  0.955298 -1.430019  1.434071 -0.088215       0
16 -0.227946  0.047462  0.373573 -0.111675       0
17  1.627912  0.043611  1.743403 -0.012714       0
19  0.104425  0.037412  0.450598 -0.923387       0

不過要注意的一件事是,如果你這樣做

df1['e'] = Series(np.random.randn(sLength), index=df1.index)

這實際上是 df1.index 上的連接。 所以如果你想有一個連接效果,我可能不完美的解決方案是創建一個索引值覆蓋你的數據域的數據框,然后使用上面的代碼。 例如,

data = pd.DataFrame(index=all_possible_values)
df1['e'] = Series(np.random.randn(sLength), index=df1.index)

要在數據框中的給定位置(0 <= loc <= 列數)插入新列,只需使用 Dataframe.insert:

DataFrame.insert(loc, column, value)

因此,如果您想在名為df的數據框的末尾添加列e ,您可以使用:

e = [-0.335485, -1.166658, -0.385571]    
DataFrame.insert(loc=len(df.columns), column='e', value=e)

value可以是一個系列、一個整數(在這種情況下,所有單元格都被這個值填充)或類似數組的結構

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html

讓我補充一下,就像hum3一樣, .loc沒有解決SettingWithCopyWarning ,我不得不求助於df.insert() 在我的情況下,誤報是由“假”鏈索引dict['a']['e']生成的,其中'e'是新列,而dict['a']是來自字典的 DataFrame。

另請注意,如果您知道自己在做什么,則可以使用pd.options.mode.chained_assignment = None切換警告,而不是使用此處給出的其他解決方案之一。

在分配新列之前,如果您有索引數據,則需要對索引進行排序。 至少在我的情況下,我必須:

data.set_index(['index_column'], inplace=True)
"if index is unsorted, assignment of a new column will fail"        
data.sort_index(inplace = True)
data.loc['index_value1', 'column_y'] = np.random.randn(data.loc['index_value1', 'column_x'].shape[0])

向現有數據框添加新列“e”

 df1.loc[:,'e'] = Series(np.random.randn(sLength))

我正在尋找一種將numpy.nan的列添加到數據框中的一般方法,而不會得到愚蠢的SettingWithCopyWarning

從以下:

  • 這里的答案
  • 這個關於將變量作為關鍵字參數傳遞的問題
  • 這種用於在線生成 NaN 的numpy數組的方法

我想出了這個:

col = 'column_name'
df = df.assign(**{col:numpy.full(len(df), numpy.nan)})

為了完整起見-使用DataFrame.eval()方法的另一種解決方案:

數據:

In [44]: e
Out[44]:
0    1.225506
1   -1.033944
2   -0.498953
3   -0.373332
4    0.615030
5   -0.622436
dtype: float64

In [45]: df1
Out[45]:
          a         b         c         d
0 -0.634222 -0.103264  0.745069  0.801288
4  0.782387 -0.090279  0.757662 -0.602408
5 -0.117456  2.124496  1.057301  0.765466
7  0.767532  0.104304 -0.586850  1.051297
8 -0.103272  0.958334  1.163092  1.182315
9 -0.616254  0.296678 -0.112027  0.679112

解決方案:

In [46]: df1.eval("e = @e.values", inplace=True)

In [47]: df1
Out[47]:
          a         b         c         d         e
0 -0.634222 -0.103264  0.745069  0.801288  1.225506
4  0.782387 -0.090279  0.757662 -0.602408 -1.033944
5 -0.117456  2.124496  1.057301  0.765466 -0.498953
7  0.767532  0.104304 -0.586850  1.051297 -0.373332
8 -0.103272  0.958334  1.163092  1.182315  0.615030
9 -0.616254  0.296678 -0.112027  0.679112 -0.622436

如果您只需要創建一個新的空列,那么最短的解決方案是:

df.loc[:, 'e'] = pd.Series()

以下是我所做的......但我對熊貓和真正的Python很陌生,所以沒有承諾。

df = pd.DataFrame([[1, 2], [3, 4], [5,6]], columns=list('AB'))

newCol = [3,5,7]
newName = 'C'

values = np.insert(df.values,df.shape[1],newCol,axis=1)
header = df.columns.values.tolist()
header.append(newName)

df = pd.DataFrame(values,columns=header)

如果我們想為 df 中新列的所有行分配一個縮放器值,例如:10:

df = df.assign(new_col=lambda x:10)  # x is each row passed in to the lambda func

df 現在將在所有行中具有 value=10 的新列“new_col”。

如果您得到SettingWithCopyWarning ,一個簡單的解決方法是復制您嘗試添加列的 DataFrame。

df = df.copy()
df['col_name'] = values
x=pd.DataFrame([1,2,3,4,5])

y=pd.DataFrame([5,4,3,2,1])

z=pd.concat([x,y],axis=1)

在此處輸入圖像描述

這是向 pandas 數據框添加新列的特殊情況。 在這里,我基於數據框的現有列數據添加了一個新功能/列。

因此,讓我們的 dataFrame 包含列“feature_1”、“feature_2”、“probability_score”,我們必須根據“probability_score”列中的數據添加一個新的“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

編碼

每當您將 Series 對象作為新列添加到現有 DF 時,您需要確保它們都具有相同的索引。 然后將其添加到 DF

e_series = pd.Series([-0.335485, -1.166658,-0.385571])
print(e_series)
e_series.index = d_f.index
d_f['e'] = e_series
d_f

在此處輸入圖像描述

您可以通過for 循環插入新列,如下所示:

for label,row in your_dframe.iterrows():
      your_dframe.loc[label,"new_column_length"]=len(row["any_of_column_in_your_dframe"])

示例代碼在這里:

import pandas as pd

data = {
  "any_of_column_in_your_dframe" : ["ersingulbahar","yagiz","TS"],
  "calories": [420, 380, 390],
  "duration": [50, 40, 45]
}

#load data into a DataFrame object:
your_dframe = pd.DataFrame(data)


for label,row in your_dframe.iterrows():
      your_dframe.loc[label,"new_column_length"]=len(row["any_of_column_in_your_dframe"])
      
      
print(your_dframe) 

輸出在這里:

any_of_column_in_your_dframe 卡路里 期間 新列長度
厄辛古爾巴哈爾 420 50 13.0
亞吉茲 380 40 5.0
TS 390 45 2.0

不是:你也可以這樣使用:

your_dframe["new_column_length"]=your_dframe["any_of_column_in_your_dframe"].apply(len)

向現有數據框添加新列的簡單方法是:

new_cols = ['a' , 'b' , 'c' , 'd']

for col in new_cols:
    df[f'{col}'] = 0 #assiging 0 for the placeholder

print(df.columns)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM