gpt4 book ai didi

python - 在 Pandas 中,如何在单个单元格中设置数字格式?

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:40 30 4
gpt4 key购买 nike

在 pandas 中,可以使用 mapapplymap 来显示一组整数或 float ,使其看起来像典型的数字格式。例如....

df['Big_num'] = df['Big_num'].map('{:,.0f}'.format)

... 会将包含 123456.789 的列转换为看起来更好的字符串:123,457。

我正在使用一个应用程序,用户将在其中执行一些操作并导致数据框中的各个单元格重新计算。结果,给定行的“数字”将变回 float ,然后需要重新格式化。

在这种情况下,您不能使用 map 功能,因为大部分列都是字符串。它会抛出一个 ValueError。这是我正在尝试做的事情的玩具版本:

import pandas as pd
import numpy as np

df_data = {'Location' : ['Denver', 'Boulder', 'San Diego', 'Reno', 'Portland',
'Eugene', 'San Francisco'], 'State' : ['co', 'co', 'ca', 'nv',
'or', 'or', 'ca'], 'Rando_num': [18.56, 5.12, 34.87, 11.22, 72.68, 42.90, 9.38],
'Other_num': [113, 260, 557, 134, 883, 422, 22]}
df = pd.DataFrame(data = df_data)
df['Big_num'] = df['Rando_num'] * df['Other_num']
df['Big_num'] = df['Big_num'].map('{:,.0f}'.format)

print(df)

add_num = input('Type a number to add to row 3 ')

df.loc[3, 'Big_num'] = df.loc[3, 'Rando_num'] * df.loc[3, 'Other_num'] + float(add_num)

#Neither of these work
#df.loc[3, 'Big_num'] = df.loc[3, 'Big_num'].map('{0:.2f}%'.format)
#df.loc['Big_num'] = df['Big_num'].map('{0:.2f}%'.format)

print(df)

我正在寻找在 [3, 'Big_num'] 处卖出的输出应该类似于

1,503

有什么想法吗?提前致谢。

最佳答案

您可以将字符串格式应用于标量。 pd.DataFrame.at针对按标签访问和设置标量值进行了优化。

add_num = float(input('Type a number to add to row 3 '))  # 123

df.at[3, 'Big_num'] = '{:,.0f}'.format(df.at[3, 'Rando_num'] *
df.at[3, 'Other_num'] + add_num)

print(df)

# Location State Rando_num Other_num Big_num
# 0 Denver co 18.56 113 2,097
# 1 Boulder co 5.12 260 1,331
# 2 San Diego ca 34.87 557 19,423
# 3 Reno nv 11.22 134 1,626
# 4 Portland or 72.68 883 64,176
# 5 Eugene or 42.90 422 18,104
# 6 San Francisco ca 9.38 22 206

关于python - 在 Pandas 中,如何在单个单元格中设置数字格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054950/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com