简体   繁体   English

如果同一行的另一列中存在空值,则将列值与前一行合并

[英]concat column values with previous row if there is null in another column in same row

I have a data frame like this,我有一个这样的数据框,

df: df:

col1      col2       col3
 1        cat          4
nan       dog         nan 
 3        tiger         3
 2        lion          9
 nan      frog         nan
 nan     elephant      nan

I want to create a data frame from this data frame that id there is nan values in col1, col2 values will be added to the previous row value.我想从这个数据框创建一个数据框,id 在 col1 中有 nan 值,col2 值将被添加到前一行值。

for example the desired output data frame will be:例如,所需的输出数据帧将是:

col1     col2             col3
 1      catdog             4
 3       tiger             3
 2     lionfrogelephant    9

How to do this using pandas ?如何使用熊猫做到这一点?

Use forward filling missing values and aggregate join :使用前向填充缺失值和聚合join

cols = ['col1','col3']
df[cols] = df[cols].ffill()
df = df.groupby(cols)['col2'].apply(''.join).reset_index()
print (df)
   col1  col3              col2
0   1.0   4.0            catdog
1   2.0   9.0  lionfrogelephant
2   3.0   3.0             tiger

Or if necessary forward filling missing values in all columns:或者,如有必要,在所有列中向前填充缺失值:

df = df.ffill().groupby(['col1','col3'])['col2'].apply(''.join).reset_index()
print (df)
   col1  col3              col2
0   1.0   4.0            catdog
1   2.0   9.0  lionfrogelephant
2   3.0   3.0             tiger

暂无
暂无

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

相关问题 根据另一列的当前行和同一列的上一行递增一列的值 - Increment values of a column based on the current row of another column and the previous row of the same column 根据上一行另一列中的值修改1列中的值 - Modify values in 1 column based on the value in another column in the previous row 如果从另一列的同一行看到新值,则重复前一行的值然后求和,然后在 Python 中重复当前行 - repeat previous row's value then sum if new values are seen from the same row of another column, then repeat current row in Python 删除 pandas 列列表中与同一行中的另一列匹配的值 - Remove the values in pandas column list that match another column in that same row 如何使用前一行值以及同一行中其他列中的值来计算pandas中列的值 - how to use previous row value as well as values in other column in same row to compute value of a column in pandas 根据Pandas中第二列的条件,用另一行的同一列的值填充特定行的列中的值 - Fill values in a column of a particular row with the value of same column from another row based on a condition on second column in Pandas 如何将列的实际行与另一列熊猫的前一行相加? - How to sum actual row of column to previous row of another column pandas? Python Pandas 函数根据另一列中的重复值将不同的值合并到一行中 - Python pandas function to concat into one row different values into one column based on repeating values in another 替换同一列中上一行的值 - Replace value from previous row in same column 向数据框中添加一个新列,其中值取决于同一列的前一行值 - Add a new column to a data-frame where values are dependent on previous row values of the same column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM