问题
I need to divide every element in a specific column in a Pandas DataFrame by 100.
By default, the .div() function in Pandas divides all elements across all columns, and attempting to specify columns to divide leaves me with only those columns.
d = {
'SYMBOL':['AAAAA','BBBBB','CCCCC'],
'ASSETS':[5, 21, 74]}
data = pd.DataFrame(d,columns=['SYMBOL','ASSETS'])
data = data['ASSETS'].div(100)
So, starting with
0 AAAAA 5
1 BBBBB 21
2 CCCCC 74
I end up getting
0 0.05
1 0.21
2 0.74
When I want
0 AAAAA 0.05
1 BBBBB 0.21
2 CCCCC 0.74
回答1:
data['ASSETS'] = data['ASSETS'].div(100)
You are overwriting your entire dataframe by assigning it back to data
回答2:
You can move symbols into the index of the dataframe, with set_index
then, divide, and lastly reset_index
:
d = {
'SYMBOL':['AAAAA','BBBBB','CCCCC'],
'ASSETS':[5, 21, 74]}
data = pd.DataFrame(d,columns=['SYMBOL','ASSETS'])
data = data.set_index('SYMBOL')
data = data.div(100)
print(data.reset_index())
Output:
SYMBOL ASSETS
0 AAAAA 0.05
1 BBBBB 0.21
2 CCCCC 0.74
来源:https://stackoverflow.com/questions/56858257/how-do-i-divide-elements-in-a-single-column-of-a-python-dataframe