简体   繁体   English

Python Pandas-在数据框中合并两列

[英]Python Pandas - Merge two columns in a dataframe

I have a pandas df that looks like this: 我有一个看起来像这样的熊猫df:

     TTL1    TTL2
0    val1    
1    val2   
2    val3
3             val4
4    val5    
5    val6   
6    val7
7             val8

and I want to make it like so: 我想这样:

     TTL1
0    val1    
1    val2   
2    val3
3    val4
4    val5    
5    val6   
6    val7
7    val8

any ideas please on how I can get this done? 关于如何完成此工作有什么想法吗?

How about conditional setting? 条件设置如何?

In [260]: df.loc[df.TTL1 == '', 'TTL1'] = df.TTL2

In [261]: df
Out[261]:
   TTL1  TTL2
0  val1
1  val2
2  val3
3  val4  val4
4  val5
5  val6
6  val7
7  val8  val8

Alternatively , using np.where 或者 ,使用np.where

In [266]: df.TTL1 = np.where(df.TTL1 == '', df.TTL2, df.TTL1)

In [267]: df
Out[267]:
   TTL1  TTL2
0  val1
1  val2
2  val3
3  val4  val4
4  val5
5  val6
6  val7
7  val8  val8

set_up 设定

df = pd.DataFrame([
        ['val1', np.nan],
        ['val2', np.nan],
        ['val3', np.nan],
        [np.nan, 'val4'],
        ['val5', np.nan],
        ['val6', np.nan],
        ['val7', np.nan],
        [np.nan, 'val8']
    ], columns=['TTL1', 'TTL2'])

simplest answer is to use combine_first 最简单的答案是使用combine_first

df.TTL1.combine_first(df.TTL2).to_frame()

   TTL1
0  val1
1  val2
2  val3
3  val4
4  val5
5  val6
6  val7
7  val8

If those blanks are actually '' then do this first 如果这些空格实际上是''那么请先执行此操作

df.replace('', np.nan, inplace=True)

yet another solution (assuming OP has NaN 's in the TTL1 column): 还有另一种解决方案(假设OP在TTL1列中具有NaN ):

In [127]: df.TTL1.fillna(df.TTL2)
Out[127]:
0    val1
1    val2
2    val3
3    val4
4    val5
5    val6
6    val7
7    val8
Name: TTL1, dtype: object

There is a bit ambiguity in the problem but the pandas method stack is used to put all values into a single column. 这个问题有点模棱两可,但是使用了pandas方法stack将所有值放入单个列中。

df.stack()

Output 输出量

0  TTL1    val1
1  TTL1    val2
2  TTL1    val3
3  TTL2    val4
4  TTL1    val5
5  TTL1    val6
6  TTL1    val7
7  TTL2    val8
dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM