下面是解释我想要的简单示例。我需要将列从第一个数据帧添加到其他:
import pandas as pd
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
'Parrot', 'Parrot'],
'Max Speed': [380., 370., 24., 26.]})
outlets = pd.DataFrame(columns = ['mac', 'x'])
outlets = outlets.append({'mac' : 1, 'x' : [*df.Animal]}, ignore_index=True)
outlets
输出为:
mac x
0 1 [Falcon, Falcon, Parrot, Parrot]
但是我真正想要的是:
mac x
0 1 Falcon
1 1 Falcon
2 1 Parrot
3 1 Parrot
请告诉我我该怎么做...
x mac
0 Falcon 1
1 Falcon 1
2 Parrot 1
3 Parrot 1
import pandas as pd
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
'Parrot', 'Parrot'],
'Max Speed': [380., 370., 24., 26.]})
outlets = pd.DataFrame(columns = ['mac', 'x'])
for animal in [*df.Animal]:
outlets = outlets.append({'mac': 1,'x': animal}, ignore_index=True)
print(outlets)
更有效:
import pandas as pd
df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
'Parrot', 'Parrot'],
'Max Speed': [380., 370., 24., 26.]})
outlets = pd.concat(
[pd.DataFrame([[1, animal]], columns=['mac', 'x']) for animal in [*df.Animal]],
ignore_index=True)
print(outlets)
输出:
Less efficient:
mac x
0 1 Falcon
1 1 Falcon
2 1 Parrot
3 1 Parrot
More efficient:
mac x
0 1 Falcon
1 1 Falcon
2 1 Parrot
3 1 Parrot