我想使用固定的列、行或值對 Pandas 資料幀執行操作。
例如:
import numpy as np
import pandas as pd
df = pd.DataFrame({'a':(1,2,3), 'b':(4,5,6), 'c':(7,8,9), 'd':(10,11,12),
'e':(13,14,15)})
df
Out[57]:
a b c d e
0 1 4 7 10 13
1 2 5 8 11 14
2 3 6 9 12 15
我想將“a”和“b”列中的值用作固定值。
# It's easy enough to perform the operation I want on one column at a time:
df.loc[:,'f'] = df.loc[:,'c'] df.loc[:,'a'] df.loc[:,'b']
# It gets cumbersome if there are many columns to perform the operation on though:
df.loc[:,'g'] = df.loc[:,'d'] / df.loc[:,'a'] * df.loc[:,'b']
df.loc[:,'h'] = df.loc[:,'e'] / df.loc[:,'a'] * df.loc[:,'b']
# etc.
# This returns columns with all NaN values.
df.loc[:,('f','g','h')] = df.loc[:,'c':'e'] / df.loc[:'a']
在 Pandas 中是否有最佳方式來做我想做的事?我在 Pandas 檔案或這個SO 執行緒中找不到有效的解決方案。我認為我不能使用.map()or .applymap(),因為我的印象是它們只能用于簡單的方程(一個輸入值)。謝謝閱讀。
uj5u.com熱心網友回復:
使用divandmul代替/and *with axis=0:
df[['g', 'h']] = df[['d', 'e']].div(df['a'], axis=0).mul(df['b'], axis=0)
print(df)
# Output
a b c d e g h
0 1 4 7 10 13 40.0 52.0
1 2 5 8 11 14 27.5 35.0
2 3 6 9 12 15 24.0 30.0
與numpy:
arr = df.to_numpy()
arr[:, [3, 4]] / arr[:, [0]] * arr[:, [1]]
# Output
array([[40. , 52. ],
[27.5, 35. ],
[24. , 30. ]])
uj5u.com熱心網友回復:
正如@Corralien 指出的那樣,最好使用 Pandas 資料框操作,例如.div(),但我也發現使用.loc[]很重要。
# Doesn't work:
df.loc[:,['f','g','h']] = df.loc[:,'c':'e'].div(df.loc[:'a'], axis=0)
# Doesn't work:
df[['f','g','h']] = df.loc[:,'c':'e'].div(df.loc[:'a'], axis=0)
# Now works.
df[['f','g','h']] = df.loc[:,'c':'e'].div(df['a'], axis=0)
目前,我不確定這是為什么。任何見解都會有所幫助,謝謝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424763.html
上一篇:Python的Pandas模塊在同一目錄中找不到檔案
下一篇:在資料框中以布林值獲取美國假期
