pandas 在条件下移动列数据 [英] Pandas shift column data upon condition
本文介绍了 pandas 在条件下移动列数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 dataframe
,看起来像这样。
Name Val Rating
0 ABC 123 B +
1 DEF 234 B +
2 567 B- NaN
3 GHI 890 D
但我希望通过检查(col ['Name'])
到下一列来转移数据(col ['Val'])
并连续转移。此外,如果发生转换,则更改行 index
值。我希望以下 dataframe
作为输出。
but instead I want to shift the data by checking (col['Name'])
to next column (col['Val'])
and successively shifting. Also if the shifting happens change the row index
value. I want the following dataframe
as output.
Name Val Rating
0 ABC 123 B +
1 DEF 234 B +
NaN 567 B -
2 GHI 890 D
有谁知道怎么做?
推荐答案
你可以通过布尔值掩码来移动行:
You can shift rows by boolean mask:
mask = pd.to_numeric(df['Name'], errors='coerce').notnull()
df[mask] = df[mask].shift(axis=1)
print (df)
Name Val Rating
0 ABC 123 B +
1 DEF 234 B +
2 NaN 567 B-
3 GHI 890 D
细节:
print (pd.to_numeric(df['Name'], errors='coerce'))
0 NaN
1 NaN
2 567.0
3 NaN
Name: Name, dtype: float64
如果确实需要将索引值替换为空
字符串可以创建帮助系列
和 reindex
。
If really need replace index values to empty
strings is possible create helper Series
and reindex
.
但不建议这样做,因为性能问题和此索引可能的某些功能应该失败。
But this is not recommended because performance problem and possible some function with this index should failed.
i = df.index[~mask]
df.index = pd.Series(range(len(i)), index=i).reindex(df.index, fill_value='')
print (df)
Name Val Rating
0 ABC 123 B +
1 DEF 234 B +
NaN 567 B-
2 GHI 890 D
这篇关于 pandas 在条件下移动列数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文