![](/img/trans.png)
[英]Adding a column to a python pandas data frame based on the value of another column
[英]Faster way to update a column in a pandas data frame based on the value of another column
我有一個熊貓數據框,其列= [A,B,C,D,... I,Z]。 數據幀中大約有800,000行,並且A,B,C,D,...列的所有這些行的值均為0。 Z的值介於[0,9]之間。 我想做的是為數據框中的所有行更新第x列的值,其中x是Z的當前值。如果x的值為0,則忽略。 數據框看起來像-
A B C D ... Z
0 0 0 0 0 ... 9
1 0 0 0 0 ... 1
2 0 0 0 0 ... 2
3 0 0 0 0 ... 3
到目前為止,這就是我所擁有的。
cols = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
for index, row in df.iterrows():
if row['Z'] != 9:
df.loc[index, cols[int(row['Z'])]] = 1
這太慢了,導致腳本在中途停止執行。 有更快或更更好的方法嗎? 我嘗試查看np.where和np.apply,但無法弄清楚語法。 這是我嘗試使用np.apply-
df.iloc[what goes here?] = df['Z'].apply(lambda x: 1 if x != 9)
上述樣本的期望輸出是-
A B C D ... Z
0 0 0 0 0 ... 9
1 0 1 0 0 ... 1
2 0 0 1 0 ... 2
3 0 0 0 1 ... 3
import numpy as np
import pandas as pd
cols = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'temp'])
df = pd.DataFrame(columns=cols[:-1])
df['Z'] = [9,1,2,3,1,5,4]
df = df.fillna(0)
df.update(pd.get_dummies(cols[df['Z']]))
print(df)
產量
A B C D E F G H I Z
0 0 0 0 0 0 0 0 0 0 9
1 0 1 0 0 0 0 0 0 0 1
2 0 0 1 0 0 0 0 0 0 2
3 0 0 0 1 0 0 0 0 0 3
4 0 1 0 0 0 0 0 0 0 1
5 0 0 0 0 0 1 0 0 0 5
6 0 0 0 0 1 0 0 0 0 4
Pandas有一個函數pd.get_dummies ,它可以完全滿足您的要求:
In [274]: pd.get_dummies(['A','C','B','D'])
Out[274]:
A B C D
0 1 0 0 0
1 0 0 1 0
2 0 1 0 0
3 0 0 0 1
通過使cols
為NumPy數組,您可以使用NumPy整數數組索引來生成所需的列標簽。 ( 'temp'
列的目的在下面說明):
In [276]: cols[df['Z']]
Out[276]: array(['temp', 'B', 'C', 'D', 'B', 'F', 'E'], dtype='<U3')
這樣get_dummies
生成此DataFrame:
In [277]: pd.get_dummies(cols[df['Z']])
Out[277]:
B C D E F temp
0 0 0 0 0 0 1
1 1 0 0 0 0 0
2 0 1 0 0 0 0
3 0 0 1 0 0 0
4 1 0 0 0 0 0
5 0 0 0 0 1 0
6 0 0 0 1 0 0
df.update(other)
非NaN值從other
DataFrame復制到df
。 由於df
沒有標記為temp
的列,因此該列中的值將被忽略。
或者, 通過將 df['Z']
與pd.get_dummies(cols[df['Z']])
串聯來構造df
:
import numpy as np
import pandas as pd
cols = np.array(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'temp'])
df = pd.DataFrame({'Z':[9,1,2,3,1,5,4]})
df = pd.concat([pd.get_dummies(cols[df['Z']]), df['Z']], axis=1)
df = df.drop('temp', axis=1)
print(df)
產量
B C D E F Z
0 0 0 0 0 0 9
1 1 0 0 0 0 1
2 0 1 0 0 0 2
3 0 0 1 0 0 3
4 1 0 0 0 0 1
5 0 0 0 0 1 5
6 0 0 0 1 0 4
請注意,如果Z
列中沒有與之對應的值,則某些列可能會丟失。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.