Python 3.x 我可以从索引中使用Pandas.apply方法吗?

Python 3.x 我可以从索引中使用Pandas.apply方法吗?,python-3.x,pandas,Python 3.x,Pandas,我想从Pandas.DataFrame创建文件 1.txt,内容为“a” 2.txt,内容为“b” 3.txt,内容为“c” 4.txt,内容为“d” 5.txt,内容为“e” import pandas as pd import numpy as np df = pd.DataFrame( { 'filename': [1, 2, 3, 4, 5], 'sex': ['a', 'b', 'c', 'd', 'e']}) #I wanted to use apply method fro

我想从Pandas.DataFrame创建文件

1.txt,内容为“a”

2.txt,内容为“b”

3.txt,内容为“c”

4.txt,内容为“d”

5.txt,内容为“e”

import pandas as pd
import numpy as np

df = pd.DataFrame(
{
 'filename': [1, 2, 3, 4, 5],
 'sex': ['a', 'b', 'c', 'd', 'e']})

#I wanted to use apply method from index. but I coundn't find the index from apply Method
df["filename"].apply(lambda x: x.to_csv(df["filename"][x....])

# This doesn't work
for i in range(len(df["filename"])):
    df["filename"].iloc[[i],[1]].to_csv(f"{df.iloc[[i],[0]]}.txt")

我怎样才能解决这个问题?请给我一些建议。

如果我理解正确,这应该可以满足您的要求:

df.apply(lambda x: open('{}.txt'.format(x.filename), 'w').write(x.sex), axis=1)
注意:您不能使用.to_csv,因为这是数据帧或序列的一种方法。它不能用于像“a”或“b”这样的字符串