簡體   English   中英

連接 dataframe 列的總和,或同一列中的兩列之間的差異 dataframe

[英]concatenated dataframe sum of a column, or difference between two columns in the same dataframe

我創建了一個從 2 個不同的 dataframe 獲得的串聯 dataframe。 concat df 的布局還可以,但是當我嘗試對一列求和時,我得到一個錯誤。 在用於 sum 列的代碼下方

TotalVolumeAsk = concatenated_df['VolumeAsk'].sum()
print ("Column Volume Ask sum:",Total)

output 是

Column Volume Ask sum: 0.010000000.023380000.009390000.061090000.004690000.010000000.011250000.070510000.004000000.041750000.007460000.000530000.004000000.001060000.008000000.052200000.010000000.004000000.001000000.020000000.069790002.390000000.00401000

我認為該列的唯一值...我該如何解決這個問題?

另外,如果我使用下面的代碼來計算兩列之間的差異,我也會遇到此錯誤。

代碼用於 2 列之間的差異:

concatenated_df['spread']=concatenated_df['b']-concatenated_df['c']

錯誤:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

感謝您的幫助。

我創建了自己的 dataframe,如果刪除列轉換為浮點的行,則會出現相同的錯誤。 導入 pandas 作為 pd

df = pd.DataFrame({'bid':['1.2', '1.4', '1.5'], 'ask':['1.5', '1.7', '2.1']})
df[['bid', 'ask']] = df[['bid', 'ask']].astype(float)#If you remove this line, then the same errors will occur
df['spred'] = df['ask'] - df['bid']

TotalAsk = df['ask'].sum()

print ("Column Ask sum:", TotalAsk)
print(df)

Output

Column Ask sum: 5.300000000000001

   bid  ask  spred
0  1.2  1.5   -0.3
1  1.4  1.7   -0.3
2  1.5  2.1   -0.6

如果在轉換之前打印列類型:

df = pd.DataFrame({'bid':['1.2', '1.4', '1.5'], 'ask':['1.5', '1.7', '2.1']})
print(df.dtypes)

Output

bid    object
ask    object

后:

df[['bid', 'ask']] = df[['bid', 'ask']].astype(float)#If you remove this line, then the same errors will occur
print(df.dtypes)

Output

bid    float64
ask    float64

這就是為什么我要詢問您的列的數據類型。 你有它 object,也就是說,不是數字。 它們中的值不是數字。

暫無
暫無

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

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