我有一个包含数千行的数据框,此示例 df 给出了存在的不同类型的行:
df = pd.DataFrame({'col1': ['1', '2', '2', '3'],
'col2': ['10', '15', '20', '30'],
'col3': ['cat', 'dog', 'cat', 'cat'],
'col4': [0.2, 0.9, 'dog', 0.5],
'col5': [None, None, 0.3, 'dog'],
'col6': [None, None, None, 0.1]})
col1
, col2
一切都很好。对于该行的其余部分,我想要 cat
, dog
, 和 catdog
成为列标题。当列标题出现在一行中时,紧随其后的任何值都应该是该列中的值。
每一行的规则:
- 如果一行只包含
cat
,十进制值进入cat
列(dog
和catdog
列 有None
)。 - 如果一行只包含
dog
,十进制值进入dog
列(cat
和catdog
列有None
). - 如果一行同时具有
cat
和dog
, 但只有 1 个小数,小数应该在catdog
下以及cat
和dog
. - 如果一行同时具有
cat
和dog
, 但 2 个十进制数字,十进制数字位于数字前面的列下方(None
在catdog
下方)。
例如,在第一行中,0.2
直接在cat
之后,所以它将进入该列(与 1
和 10
来自 col1/col2
的行)。
在第三行,0.3
, 在“cat
, dog
”之后,所以 0.3
进入所有列:cat
, dog
, 和 catdog
.
期望的输出:
dfoutput = pd.DataFrame({'col1': ['1', '2', '2', '3'],
'col2': ['10', '15', '20', '30'],
'cat': [0.2, None, 0.3, 0.5],
'dog': [None, 0.9, 0.3, 0.1],
'catdog': [None, None, 0.3, None]})
最佳答案
使用np.select
和np.where
:
cond1 = (df['col3']=='cat') & (df['col4']!='dog')
cond2 = (df['col3']=='cat') & (df['col4']=='dog')
cond3 = df['col3']=='dog'
cond4 = df['col5']=='dog'
cond5 = df['col4']=='dog'
df['cat'] = np.select([cond1, cond2], [df['col4'], df['col5']], None)
df['dog'] = np.select([cond3,cond4,cond5], [df['col4'], df['col6'], df['col5']], None)
df['catdog'] = np.where(cond2, df['col5'], None)
df.drop(['col3','col4','col5','col6'], axis=1, inplace=True)
print(df)
输出:
col1 col2 cat dog catdog
0 1 10 0.2 None None
1 2 15 None 0.9 None
2 2 20 0.3 0.3 0.3
3 3 30 0.5 0.1 None
关于python - 将某些格式奇怪的 df 行更改为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682771/