【问题标题】:Please simplify my code or make it much more advance Python programmer请简化我的代码或让它更高级 Python 程序员
【发布时间】:2019-02-02 15:49:45
【问题描述】:
import pandas as pd
df = pd.DataFrame({'col1': [1, 2, 3], 'col2': [2, 3, 4]})

for i=0 to range(len(df))
    print(df.iloc[i]['col1'] + '-' + df.iloc[i]['col2'])

我想使用:(但它给了我错误)

for d in df:
    print(d['col1'] + '-' + d['col2'])
# I want output
# 2-3
# 3-4

仅限简单的 Pandas 问题...

【问题讨论】:

  • 你能解释一下吗,你需要什么?
  • #我要输出#2-3#3-4
  • 你可以把for val in df['col1']:改成for val in df['col1'].astype(str) + ' - ' df['col2'].astype(str):
  • 谢谢!你说对了! .astype 和 val !!!你在读什么 Python 字典??!!
  • 不,不是字典,类似dict in pandasSeries

标签: python pandas dataframe


【解决方案1】:
for index, row in df.iterrows():
     print(row['col1'], row['col2'])

感谢@Jezrael link 我能够将我的代码更改为更具前瞻性的代码,而不是我的,有点老派的 LOL

请“点击”检查正确答案。

Zip 方法也正确,但会限制代码的灵活性。例如,我可以以不同的顺序再次将我的数据转换为 string.format。所以 iterrows 是这样做的方法。虽然,我已经用我的旧代码完成了我的项目。但我还是把它改成了新的和正确的方法。

【讨论】:

  • 是的,或者itertuples更快一点。
  • 但是如果检查this,最好使用一些矢量化函数(如果存在);)
  • @user122289 虽然您的代码可能作为答案正确但详细说明您的代码的作用,它可以提高您的答案质量。查看文章:How do I write a good answer?
  • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和文档链接。如果没有围绕它的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请编辑您的答案。
  • 所以这将删除我在 StackOverflow 中的“询问禁令”?
【解决方案2】:

IIUC:

你想打印每一行列'col1'

print(*df.col1, sep='\n')

【讨论】:

  • #我要输出#2-3#3-4
【解决方案3】:

如果要循环所有列:

for col in df:
    print(df[col])

有什么相似之处:

for col in df.columns:
    print(df[col])

或者如果需要循环列col1的值:

for val in df['col1']:
    print(val)

【讨论】:

  • 如何按行循环?
  • @user122289 - 使用iterrowsitertuples,检查this
猜你喜欢
  • 1970-01-01
  • 2015-06-08
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多