[英]How to loop through columns in a dataframe?
I have a dataframe with many metric columns all containing float output. 我有一个包含许多公制列的数据框都包含浮点输出。 I need to round them all to four digits.
我需要将它们全部四舍五入到四位数。 I want to loop through all the columns to do this.
我想循环遍历所有列来执行此操作。
import numpy as np
import pandas as pd
test_df = pd.DataFrame(np.random.randn(10,4), columns=['a','b','c','d'])
metrics = test_df.columns
metrics = metrics.tolist()
for x in metrics:
test_df.x = np.round(test_df.x, 4)
However, this gives me the error: 但是,这给了我错误:
AttributeError: 'DataFrame' object has no attribute 'x'
Whats the best way to do this? 什么是最好的方法呢?
import functools
test_df.apply(functools.partial(np.round, decimals=4))
if you want to iterate through columns, it's straightforward: 如果你想遍历列,它很简单:
for c in test_df.columns:
test_df[c] = np.round(test_df[c], 4)
what you tried to do that's busted has to do with attribute access in python. 你试图做的事情已经被破坏了与python中的属性访问有关。 when you try to do
test_df.x
, that x
has absolutely nothing to do with the x
in your for
loop. 当你尝试做
test_df.x
时, x
与你的for
循环中的x
完全无关。 this would have the same result: 这会有相同的结果:
for unused_value in metrics:
test_df.x = ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.