我想对DataFrame中所有index结尾为“_count”的行的数据取整数,下面是我的DataFrame
我测试过了2段代码,但是好像都没有用
for index, row in a.iterrows():
if row.index.values[0].endswith('_count'):
"{:.0f}".format(row['units'])
for index, row in a.iterrows():
if row.index.values[0].endswith('_count'):
row['units'].apply(lambda x : format(x, '.0f') if pd.notnull(x) else '')
请问有什么办法能达到我想要的效果
for index, row in a.iterrows():
if index.endswith('_count'):
a.loc[index, 'units'] = row['units'].apply(lambda x: round(x) if pd.notnull(x) else None)
gpt:您可以使用pandas中的.loc属性来选择行和列,并使用.astype()方法将选定的数据转换为整数。
下面是一个示例代码:
import pandas as pd
# 创建示例数据
data = {'item_count': [3.0, 5.6, 7.9],
'unit_count': [1.2, 2.3, 4.5],
'amount': [10.5, 20.0, 30.75]}
df = pd.DataFrame(data)
# 选择以“_count”结尾的列,并将其转换为整数
count_cols = [col for col in df.columns if col.endswith('_count')]
df.loc[:, count_cols] = df.loc[:, count_cols].astype(int)
print(df)
输出结果如下:
item_count unit_count amount
0 3 1 10.50
1 5 2 20.00
2 7 4 30.75
在示例中,我们首先使用列表推导式来选择以“_count”结尾的列名。然后,我们使用.loc属性选择这些列和所有行,并使用.astype()方法将它们转换为整数。
请注意,我们将整个.loc选择器的结果赋值回DataFrame中的相同位置。这是因为.loc返回一个对原始DataFrame的引用,因此我们可以直接修改原始数据。
能获取到DataFrame了,就直接loc获取并修改行就行,示例代码:
# 找到所有以_count结尾的索引
target_index = [index for index in df.index if index.find('_count') != -1]
# 通过applymap修改指定行所有数据
df.loc[target_index, :] = df.loc[target_index, :].applymap(lambda x:'%.0f' % x if x else 0)
有帮助的话,请点采纳该答案~