Pre*_*nde 5 python dataframe pandas
我有一个包含长数字的列的数据框。我正在尝试将数字列中的所有值转换为逗号分隔的数千个值。
df
col_1 col_2
Rooney 34590927
Ronaldo 5467382
John 25647398
Run Code Online (Sandbox Code Playgroud)
如何迭代并获得以下结果?
预期结果:
col_1 col_2
Rooney 34,590,927
Ronaldo 5,467,382
John 25,647,398
Run Code Online (Sandbox Code Playgroud)
您可以使用字符串格式,
df['col_2'] = pd.to_numeric(df['col_2'].fillna(0), errors='coerce')
df['col_2'] = df['col_2'].map('{:,.2f}'.format)
Run Code Online (Sandbox Code Playgroud)
请记住, col_2 现在将是字符串而不是整数。
col_1 col_2
0 Rooney 34,590,927.00
1 Ronaldo 5,467,382.00
2 John 25,647,398.00
Run Code Online (Sandbox Code Playgroud)
将格式函数应用于 col_2
df = df.assign(col_2=df.col_2.astype(int).apply('{:,}'.format))
col_1 col_2
0 Rooney 34,590,927
1 Ronaldo 5,467,382
2 John 25,647,398
Run Code Online (Sandbox Code Playgroud)