英文:
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
a b c
0 car new york queens
1 bus california los angeles
2 aircraft illinois chicago
3 rocket texas houston
4 subway maine augusta
5 train florida miami
Mon script:
for index, row in df.iterrows():
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:
car
queens
new york
bus
los angeles
california
...
答案1
得分: 2
循环较慢,但如果使用row
Series
,则仍然可以实现:
for index, row in df.iterrows():
print(row["a"], row["c"], row["b"], sep="\n")
另一个方法是将列转换为NumPy数组:
for a, b, c in df[['a', 'b', 'c']].to_numpy():
print(a, c, b, sep="\n")
或者使用zip
:
for a, b, c in zip(df['a'], df['b'], df['c']):
print(a, c, b, sep="\n")
英文:
Looping is slow, but possible if use row
Series
:
for index, row in df.iterrows():
print(row["a"], row["c"], row["b"], sep="\n")
Another idea is convert columns to numpy array:
for a, b, c in df[['a','b','c']].to_numpy():
print(a, c, b, sep="\n")
Or zip
:
for a, b, c in zip(df['a'],df['b'],df['c']):
print(a, c, b, sep="\n")
答案2
得分: 2
使用apply方法来实现这一点:
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:
df.apply(lambda row: print(f"{row['a']}\n{row['c']}\n{row['b']}\n"), axis = 1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论