我在Python 3.6中使用Pandas。 我的脚本加载了一个包含多个工作表的Excel文件。 在某些工作表中,行在两列上具有数字值或字符串值。 运行脚本后,数值会分为两列,但是我不能在第二列上复制第一列的字符串值。
对于数值,我正在使用:
df=df[['ID_Test']].join(df[pd_column].str.split(':',expand=True)).rename(columns={0: pd_column, 1: ''})
字符串值的第二列保持空白(无),并且必须使用与第一列相同的值进行更新
如果我使用:
df[''] = df[pd_column]
,第二列['']完全更新为第一列的值(覆盖数字值),我没有找到任何针对我的关注的解决方案。
数据输入:
ID_Test_1 Test_1
Indicator_1 AAAAAAA
Indicator_2 2.745 : 2.03
Indicator_3 BBBBBBBB
Indicator_4 -5.013 : -5.013
Indicator_5 CCCCCCCC
实际输出:(错误)
ID_Test_1 Test_1
Indicator_1 AAAAAAA None
Indicator_2 2.745 2.03
Indicator_3 BBBBBBBB None
Indicator_4 -5.013 -5.013
Indicator_5 CCCCCCCCC None
所需的输出:
ID_Test_1 Test_1
Indicator_1 AAAAAAA AAAAAAA
Indicator_2 2.745 2.03
Indicator_3 BBBBBBBB BBBBBBBB
Indicator_4 -5.013 -5.013
Indicator_5 CCCCCCCCC CCCCCCCCC
第二列不能带有标签
答案 0 :(得分:0)
基于示例数据和代码。我刚刚将ffill(1)
添加到join
pd_column = 'Test_1'
(df[['ID_Test_1']].join(df[pd_column].str.split('\s+:\s+',expand=True).ffill(1))
.rename(columns={0: pd_column, 1: ''}))
Out[29]:
ID_Test_1 Test_1
0 Indicator_1 AAAAAAA AAAAAAA
1 Indicator_2 2.745 2.03
2 Indicator_3 BBBBBBBB BBBBBBBB
3 Indicator_4 -5.013 -5.013
4 Indicator_5 CCCCCCCC CCCCCCCC