python - 附加数据框但从每个 table 中删除空列

python - Append dataframe but remove null column from each table

我在 python 中有两个数据帧:

df1

Column1 Column2 Column3 Column4 Column5
1a 123 RJ 12.1 test1
2a 432 MT 23.2 test3
3a 234 DR 34.3 test5

df2

Column1 Column3 Column6
1a RJ 695
2a MT 568
3a DR 232

我希望将它们附加在一起并将它们保存为 CSV,用竖线分隔。

但是当我简单地追加时,有很多列为空:


df3 = df1.append(df2, ignore_index=True)
Column1 Column2 Column3 Column4 Column5 Column6
1a 123 RJ 12.1 test1
2a 432 MT 23.2 test3
3a 234 DR 34.3 test5
1a RJ 695
2a MT 568
3a DR 232

然后写入 CSV 时给我这个结果:

df3.to_csv('df3.csv', sep='|', index=False) #I will also remove header ',header=False'

第 1 列 |专栏2 |专栏3 |专栏4 |第 5 列|第 6 列|

1a| 123|RJ| 12.1|测试 1||

2a| 432|公吨| 23.2|测试 3||

3a|234|DR| 34.3|测试5||

1a| |RJ|| |695|

2a| |公吨|| |568|

3a| |博士|| |232 |

但我需要的结果是这个输出,忽略空值(不用担心 header):

第 1 列 |专栏2 |专栏3 |专栏4 |第 5 列|第 6 列|

1a|123|RJ|12.1|test1

2a|432|MT|23.2|test3

3a|234|DR|34.3|test5

1a|RJ|695

2a|MT|568

3a|DR|232

有什么想法吗?提前致谢。

我试过下面这段代码,但仍然得到 'NaN'

pipe_delim_rows = df3.apply(lambda x: '|'.join([str(v) for v in x.values if v not in (np.nan, '', None)]), axis=1)

with open('file.txt', 'w') as f:
    for item in pipe_delim_rows:
        f.write(item + '\n')

除非我误会了,否则你只需要 df1 在 df2 之上。

如果是这种情况,只需将它们都写到同一个文件中即可。如果您不关心 headers 或列间距,则无需创建第三个 DataFrame。

import pandas as pd

df1 = pd.DataFrame({'Column1': {0: '1a', 1: '2a', 2: '3a'},
                    'Column2': {0: 123, 1: 432, 2: 234},
                    'Column3': {0: 'RJ', 1: 'MT', 2: 'DR'},
                    'Column4': {0: 12.1, 1: 23.2, 2: 34.3},
                    'Column5': {0: 'test1', 1: 'test3', 2: 'test5'}})
df2 = pd.DataFrame({'Column1': {0: '1a', 1: '2a', 2: '3a'},
                    'Column3': {0: 'RJ', 1: 'MT', 2: 'DR'},
                    'Column6': {0: 695, 1: 568, 2: 232}})

with open('file.txt', 'w', newline='') as f:
    df1.to_csv(f, sep='|', index=False, header=False)
    df2.to_csv(f, sep='|', index=False, header=False)

File.txt

1a|123|RJ|12.1|test1
2a|432|MT|23.2|test3
3a|234|DR|34.3|test5
1a|RJ|695
2a|MT|568
3a|DR|232