我们如何替换数据框中的特定值,以使替换等于这些特定值所在的第i列的顺序?例如,我有这个DF:
A B C
0 0 1
1 0 0
1 0 0
0 1 0
1 0 1
Run Code Online (Sandbox Code Playgroud)
用第1列所在的第i列(第1,第2,第3等)的顺序替换此数据框中的所有1,以便它像这样松散:
A B C
0 0 3
1 0 0
1 0 0
0 2 0
1 0 3
Run Code Online (Sandbox Code Playgroud)
这是我认为可行的,但它没有:
DF_2= [(0 if i== 0 else j for i in DF.iloc[:,j] ) for j in range(DF.shape[1]) ]
Run Code Online (Sandbox Code Playgroud)
如果只有1和0值,您可以多numpy的阵列转换通过values使用np.arrange:
print (np.arange(1, len(df.columns)+1))
[1 2 3]
print (df.values * np.arange(1, len(df.columns)+1))
[[0 0 3]
[1 0 0]
[1 0 0]
[0 2 0]
[1 0 3]]
df = pd.DataFrame(df.values * np.arange(1, len(df.columns)+1),
index=df.index, columns=df.columns)
print (df)
A B C
0 0 0 3
1 1 0 0
2 1 0 0
3 0 2 0
4 1 0 3
Run Code Online (Sandbox Code Playgroud)
更一般的解决方案,(if 0和另一个数字)是将值转换为bool:
print (df)
A B C
0 0 0 4
1 1 0 0
2 1 0 0
3 0 6 0
4 1 0 1
df = pd.DataFrame(df.astype(bool).values * np.arange(1, len(df.columns)+1),
index=df.index, columns=df.columns)
print (df)
A B C
0 0 0 3
1 1 0 0
2 1 0 0
3 0 2 0
4 1 0 3
Run Code Online (Sandbox Code Playgroud)
感谢您提供其他解决方案(Jon Clements和MaxU):
df = df.replace({col: {1: n} for n, col in enumerate(df.columns[1:], 2)})
print (df)
A B C
0 0 0 3
1 1 0 0
2 1 0 0
3 0 2 0
4 1 0 3
Run Code Online (Sandbox Code Playgroud)
df = df * np.arange(1, df.shape[1]+1)
print (df)
A B C
0 0 0 3
1 1 0 0
2 1 0 0
3 0 2 0
4 1 0 3
Run Code Online (Sandbox Code Playgroud)
时间:
N = 100
cols = ['col' + str(i) for i in range(N)]
df = pd.DataFrame(np.random.choice([0,1], size=(100000,N)), columns=cols)
[100000 rows x 100 columns]
#print (df)
In [101]: %timeit pd.DataFrame(df.values * np.arange(1, len(df.columns)+1), index=df.index, columns=df.columns)
10 loops, best of 3: 25.1 ms per loop
In [102]: %timeit df.replace({col: {1: n} for n, col in enumerate(df.columns[1:], 2)})
1 loop, best of 3: 1.39 s per loop
In [103]: %timeit df * np.arange(1, df.shape[1]+1)
10 loops, best of 3: 21 ms per loop
#Wen solution
In [104]: %timeit (df.mul(list(range(1, len(df.columns)+1))))
10 loops, best of 3: 38.7 ms per loop
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |