我开始在 python
中编码( Pandas
图书馆)因为我的工作。
这是一个口袋妖怪的例子,但我的真实dataframe
更复杂。我不知道是否可以在 Pandas 中做到这一点。
我的 dataframe
就好像:
Pokemon_Master Pokemon
1 ASH pikachu
2 ASH squirtle
3 ASH charmander
4 BROOKE onix
5 BROOKE charmander
6 MISTY squirtle
7 MISTY charmander
8 GARY onix
9 PROF OAK pikachu
我要做的是:检查每个 Pokemon 属于哪个 Pokemon_Master 并制作
.txt
每个 Pokemon_Master 的输出格式如下:Ash_pokemons.txt 或 Brooke_pokemons.txt 等。每个文件必须包含每个 Master 拥有的 pokemons,例如每个.txt
当他们在 dataframe
中发现 pokemon 时,文件将逐渐与前一个连接。 .此外,输出文本文件将根据 Pokemon_Master 调用。
例如:
文件ASH.txt里面
pikachu
squirtle
charmander
并在文件 BROOKE.txt 中
onix
charmander
squirtle
等等..
我发现了很多基本功能,比如
loc
, iterrows
concatenate
或 append
(用于加入文件),但我找不到如何加入所有这些来开发我的代码的方法。
最佳答案
IIUC,尝试:
for n, g in df.groupby('Pokemon_Master'):
g[['Pokemon']].agg(' '.join).to_csv(f'{n}.txt', sep=' ',
index=False,
header=False)
如果 Python 版本低于 3.6:
尝试,
for n, g in df.groupby('Pokemon_Master'):
g[['Pokemon']].agg(' '.join).to_csv('{}.txt'.format(n), sep=' ',
index=False,
header=False)
关于python - 根据2列中的多个值输出多个文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61860052/