连接pandas数据帧的多个列,包括少数列中的布尔值

2024-04-24 13:13:19 发布

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

我是python新手。在我的项目中,我需要连接pandas数据帧的多个列来创建派生列。“我的数据框”包含几个列,只有真值和假值。我使用下面的代码来执行连接操作

df_input["combined"] = [' '.join(row) for row in df_input[df_input.columns[0:]].values]

运行代码时出现以下错误

^{pr2}$

你能请专家帮我解决这个问题吗?在

提前谢谢


Tags: columns数据项目代码inpandasdffor
2条回答

您可以使用astype(str)Bool列进行强制转换,并使用向量化版本将这些列连接起来,如下所示

from StringIO import StringIO
import pandas as pd

st = """
col1|col2|col3
1|hello|True
4|world|False
7|!|True
"""
df = pd.read_csv(StringIO(st), sep="|")

print("my sample dataframe")
print(df.head())

print("current columns data types")
print(df.dtypes)

print("combining all columns with mixed datatypes") 
df["combined"] = df["col1"].astype(str)+" "+df["col2"]+ " " +df["col3"].astype(str)

print("here's how the data looks now")
print(df.head())

print("here are the new columns datatypes")
print(df.dtypes)

脚本的输出:

^{pr2}$

如您所见,新的combined包含连接数据。在

动态连接

要动态地执行连接,下面是如何编辑我前面的示例:

from StringIO import StringIO
import pandas as pd

st = """
col1|col2|col3
1|hello|True
4|world|False
7|!|True
"""
df = pd.read_csv(StringIO(st), sep="|")

print("my sample dataframe")
print(df.head())

print("current columns data types")
print(df.dtypes)

print("combining all columns with mixed datatypes") 
#df["combined"] = df["col1"].astype(str)+" "+df["col2"]+ " " +df["col3"].astype(str)

all_columns = list(df.columns) 
df["combined"] = "" 

for index, column_name in enumerate(all_columns):
    print("current column {column_name}".format(column_name=column_name))
    df["combined"] = df["combined"] + " " +df[column_name].astype(str)

print("here's how the data looks now")
print(df.head())

print("here are the new columns datatypes")
print(df.dtypes)

让我们试试astype

df_input["combined"] = [' '.join(row.astype(str)) for row in df_input[df_input.columns[0:]].values]

相关问题 更多 >