打印 pandas 行的单元格为字符串

huangapple go评论130阅读模式
英文:

Print pandas rows cells as string

问题

我的输出:

0 car

1 bus

2 aircraft

3 rocket

4 subway

5 train

英文:

I'm trying to print a data frame where each cell appears as a string:

Dataset

  1. a b c
  2. 0 car new york queens
  3. 1 bus california los angeles
  4. 2 aircraft illinois chicago
  5. 3 rocket texas houston
  6. 4 subway maine augusta
  7. 5 train florida miami

Mon script:

  1. for index, row in df.iterrows():
  2. print(df["a"], "\n", testes["c"], "\n", testes["b"])

My output:

0 car

1 bus

2 aircraft

3 rocket

4 subway

5 train

Name: a, dtype: object

...

Good output:

  1. car
  2. queens
  3. new york
  4. bus
  5. los angeles
  6. california
  7. ...

答案1

得分: 2

循环较慢,但如果使用row Series,则仍然可以实现:

  1. for index, row in df.iterrows():
  2. print(row["a"], row["c"], row["b"], sep="\n")

另一个方法是将列转换为NumPy数组:

  1. for a, b, c in df[['a', 'b', 'c']].to_numpy():
  2. print(a, c, b, sep="\n")

或者使用zip

  1. for a, b, c in zip(df['a'], df['b'], df['c']):
  2. print(a, c, b, sep="\n")
英文:

Looping is slow, but possible if use row Series:

  1. for index, row in df.iterrows():
  2. print(row["a"], row["c"], row["b"], sep="\n")

Another idea is convert columns to numpy array:

  1. for a, b, c in df[['a','b','c']].to_numpy():
  2. print(a, c, b, sep="\n")

Or zip:

  1. for a, b, c in zip(df['a'],df['b'],df['c']):
  2. print(a, c, b, sep="\n")

答案2

得分: 2

使用apply方法来实现这一点:

  1. df.apply(lambda row: print(f"{row['a']}\n{row['c']}\n{row['b']}\n"), axis=1)
英文:

One way to achieve that is using apply:

  1. df.apply(lambda row: print(f"{row['a']}\n{row['c']}\n{row['b']}\n"), axis = 1)

huangapple
  • 本文由 发表于 2023年1月9日 17:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定