Python Pandas : appending information to row while looping through dataframe

标签 python pandas loops append

我想知道一种在循环中将信息 append 到数据帧的更好方法。具体来说,以有条件的方式将信息列添加到数据帧中。下面的代码在技术上是可行的,但除了它很草率之外,更重要的是,当所有内容都转换为字符串时,每个单元格中的数据类型等信息都会丢失。任何提示都会很棒。

raw_data = {'first_name': ['John', 'Molly', 'Tina', 'Jake', 'Amy'], 
'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'], 
'age': [42, 20, 16, 24, '']}
df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age'])
headers = df.columns.values
count = 0
for index, row in df.iterrows():
    count += 1
    if row['age'] > 18:

        adult = True
    else:
        adult = False
    headers = np.append(headers,'ADULT')
    vals = np.append(row.values,adult)
    if count == 1:
        print ','.join(headers.tolist())
        print str(vals.tolist()).replace('[','').replace(']','').replace("'","")
    else:
        print str(vals.tolist()).replace('[','').replace(']','').replace("'","")

最佳答案

这似乎给出了您想要的结果(至少,它与您的循环结果相同):

df['ADULT'] = np.where(pd.to_numeric(df.age) > 18, True, False)

>>> df
  first_name last_name age  ADULT
0       John    Miller  42   True
1      Molly  Jacobson  20   True
2       Tina       Ali  16  False
3       Jake    Milner  24   True
4        Amy     Cooze      False

正如@Wen 所指出的,这更加更加简单:

df['ADULT'] = pd.to_numeric(df.age) > 18

关于Python Pandas : appending information to row while looping through dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566746/

相关文章:

java - 在循环中生成随机数

python - 如何将 for 循环的结果存储为单个数组?

Python 在每一列中计数和分组 0's and 1' s

python - 将 DataFrame 乘以不同形状的 DataFrame(或系列)

python - 仅更新到期日期大于 python 最大日期 - 2261 - 无法将浮点 NaN 转换为整数的行

c# - C# 中的循环反转加速应用程序

python - 降低 python for 循环的时间复杂度

python - MacPorts 说当运行 "python --version"时我仍然有 Python 2.7

python分组和进一步分组

python - cx_Freeze 和 pyinstaller 的 ImportError