Pandas:如何更改行的值的数据类型?

2024-09-22 16:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

actor          Daily Total   actor1  actor2
Day
2019-01-01     25            10       15
2019-01-02     30            15       15
Avg            27.5          12.5     15.0

如何将“Avg”行的数据类型更改为整数?如何舍入行中的值?你知道吗


Tags: 数据整数avgtotaldailyactor数据类型day
2条回答

使用loc访问索引,然后使用apply中的numpy.round。你知道吗

import numpy as np

df.loc['Avg'] = df.loc['Avg'].apply(np.round)

在add new row filled by floats中,所有列都更改为floats

可能的解决方案是^{}并转换所有列:

df = df.round().astype(int)

或添加新的Series转换为integer

df = df.append(df.mean().rename('Avg').round().astype(int))
print (df)
            Daily Total  actor1  actor2
actor                                  
2019-01-01           25      10      15
2019-01-02           30      15      15
Avg                  28      12      15

如果要仅转换行值由整数填充的列:

d = dict.fromkeys(df.columns[df.loc['Avg'] == df.loc['Avg'].astype(int)], 'int')
df = df.astype(d)
print (df)
            Daily Total  actor1  actor2
actor                                  
2019-01-01         25.0    10.0      15
2019-01-02         30.0    15.0      15
Avg                27.5    12.5      15

相关问题 更多 >