如何在 python 中合并多个数据框后,在print()中添加空格?

2024-09-30 22:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下:

import numpy as np 
import pandas as pd 

df = pd.read_csv('DelayedFlights.csv')

df["final"] = 
df["Year"].map(str)+df["FlightNum"].map(str)+df["Origin"]+df["Dest"]

print(df["final"].head()) #map converts the non string data types to string

输出显示:

^{pr2}$

我想要的输出:

0    2008 335 IAD TPA
1    2008 3231 IAD TPA
2    2008 448 IND BWI
3    2008 3920 IND BWI
4    2008 378 IND JAX
Name: final, dtype: object

Tags: csv代码importnumpymapdfstringas
3条回答
add_space = lambda x: str(x) + " "
df["final"] = df["Year"].map(add_space) + df["FlightNum"].map(add_space) + df["Origin"].map(add_space) + df["Dest"]

不是pandas专家,但是从docs(https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html)和您的示例中可以看出map方法可以接受一个函数,因此如果您在格式化时需要一个额外的空格,只需创建一个lambda将其转换为字符串,然后在调用时添加一个额外的空格。在

或者,使用format

^{pr2}$

你想要:

df["final"] = df["Year"].map(str)+ ' ' + df["FlightNum"].map(str)+ ' ' + df["Origin"]+ ' ' + df["Dest"]

单线选项:

df['final'] =  df.apply(lambda x: ' '.join([str(x['Year']), str(x['FlightNum']), x['Origin'], x['Dest']]), axis=1)

对于合并所有列中的文本的动态函数:

^{pr2}$

或受自定义列表限制:

cols = ['Year','FlightNum','Origin','Dest']
df['final'] = df.apply(lambda row: ' '.join([str(col) for col in row if col in cols), axis=1)

使用format

df['final'] = df.apply(lambda row: '{} {} {} {}'.format(row['Year'], row['FlightNum'], row['Origin'], row['Dest']), axis=1)

相关问题 更多 >