问题
This is the code:
import pandas as pd
from pandas import Series, DataFrame
import numpy as np
import matplotlib.pyplot as plt
df.head(3).style.format({'Budget': "€ {:,.0f}"})
Year Project Entity Participation Country Budget
0 2015 671650 - MMMAGIC - 5G FUNDACION IMDEA NETWORK* Participant Spain € 384,000
1 2015 671650 - MMMAGIC - 5G ROHDE & SCHWARZ GMBH* Participant Germany € 12,000
2 2015 671650 - MMMAGIC - 5G SAMSUNG ELECTRONICS (UK) LIMITED Coordinator UnitedKingdom € 997,500
datos1 = (df[(df['Participation'].str.contains('Coordinator')) & (df.Country.str.count('Spain'))])
datos2 = 'Las participaciones en proyectos como coordinador son='
datos4= 'El presupuesto en Euros es ='
display(datos1)
print(datos2, datos1.Country.str.count('Spain').sum())
print(datos4, datos1.Budget.sum())
Year Project Entity Participation Country Budget
2015 671598 - 5G-CROSSHAUL UNIVERSIDAD CARLOS III DE MADRID* Coordinator Spain 899471.88
2015 671517 - SONATA - 5G ATOS SPAIN SA* Coordinator Spain 602437.50
2015 671704 - CHARISMA - 5G FUNDACIO PRIVADA I2CAT *FI2CAT Coordinator Spain 557312.50
I want to have the same result with the budget in euros, i tried with this code:
display(datos4, datos1.Budget.sum().style.format('€ {0:,.0f}'))
Update:
display(datos4, datos1.Budget.sum().style.format('€ {0:,.0f}'))
This line was solve with this code:
print(datos4, '€ {0:,.0f}'.format(datos1.Budget.sum()))
Now, i only have problems with the style format in the budget, i tried like to fix with this code:
datos1 = (df[(df['Participation'].str.contains('Coordinator'))
& (df.Country.str.contains('Greece'))
& (df.Budget.apply('€ {0:,.0f}'.format))])
or
df['Budget']=df.Budget.apply('€ {0:,.0f}'.format)
datos1 = (df[(df['Participation'].str.contains('Coordinator'))
& (df.Country.str.contains('Greece'))])
i have errors with the code, please any idea?
回答1:
I advise you not to mix logic with appearance. Create the table according to logic, and then format it. Try this code:
datos1= df.loc[ \
df.Participation. \
str.contains('Coordinator',case=False) \
& df.Country. \
str.contains('Greece',case=False) ]
datos1_pretty= datos1.style.format({"Budget":'€ {0:,.0f}'})
You can specify more columns in the dict.
回答2:
datos1.Budget.sum()
is the sum of a series, which returns a float
, so you can't apply Pandas style.format
to it. Try this:
'€ {0:,.0f}'.format(datos1.Budget.sum())
For the table: df['Budget'] = df.Budget.apply('€ {0:,.0f}'.format)
, if you want to have formatted strings in the Budget
column. style.format
only works when you have an html frontend, i.e. jupyter.
来源:https://stackoverflow.com/questions/59069000/pandas-python-format-for-values