在Pandas中,如何水平连接并交错列?

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

In Pandas, how to concatenate horizontally with interleaving the columns?

问题

我有两个 .csv 文件 A 和 B,它们看起来像:

A:Col1,Col2,Col3

B:Col1,Col2,Col3

这两个 .csv 文件中的列名是相同的。我应该如何将它们水平连接在一起,使得结果文件 C 看起来像:

C:Col1(来自 A),Col1(来自 B),Col2(来自 A),Col2(来自 B)....

可以考虑使用 pd.concat([A,B], axis=1),但这会将一个文件的列放在另一个文件的后面。我希望它们像我上面展示的那样交错排列。

英文:

I have two .csv files A and B which look like

A : Col1, Col2, Col3

B: Col1, Col2, Col3

The column names are identical in both the .csv files. How to I concatenate them horizontally so that
the resultant file C looks like

C: Col1 (from A), Col1 (from B), Col2 (from A), Col2 (from B)....

Can think of pd.concat([A,B], axis=1) but that will place columns of one file after another. I want them interleaved in the way I have shown above.

答案1

得分: 2

我觉得也许你可以使用循环来迭代每一列,类似以下的方式:

import pandas as pd

data1 = pd.read_csv('fileA.csv')
data2 = pd.read_csv('fileB.csv')

# 创建一个空的数据框来保存结果
data_interleaved = pd.DataFrame()

# 交错插入列
for column in data1.columns:
    data_interleaved[f'{column}_from_A'] = data1[column]
    data_interleaved[f'{column}_from_B'] = data2[column]

df_interleaved.to_csv('fileC.csv', index=False)

这种方法需要两个文件具有相同数量的行,否则可能会出现问题。如果它们的行数不相同,但你仍然想要合并它们,你需要决定如何处理这种差异的策略(例如,用NaN或某个特定的值填充缺失值)。

英文:

I think maybe you can use loop to iterate over each column, something like the below:

import pandas as pd

data1 = pd.read_csv('fileA.csv')
data2 = pd.read_csv('fileB.csv')

# Create an empty dataframe to hold the result
data_interleaved = pd.DataFrame()

# Interleave the columns
for column in data1.columns:
    data_interleaved[f'{column}_from_A'] = data1[column]
    data_interleaved[f'{column}_from_B'] = data2[column]

df_interleaved.to_csv('fileC.csv', index=False)

This method need both files to have the same number of rows, otherwise there may be issues. If they do not have the same number of rows but you still want to merge them, you will need to decide on a strategy to handle the discrepancy (for example, filling missing values with NaN or with some specific value).

huangapple
  • 本文由 发表于 2023年7月14日 05:37:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683392.html
匿名

发表评论

匿名网友

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

确定